[leetcode]Valid Palindrome @ Python

时间:2023-03-09 09:02:36
[leetcode]Valid Palindrome @ Python

原题地址:https://oj.leetcode.com/problems/valid-palindrome/

题意:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

解题思路:将不是字母的字符去掉,然后转换成小写,然后简单的回文判断。

代码:

class Solution:
# @param s, a string
# @return a boolean
def isPalindrome(self, s):
if s == '':
return True
else:
sTmp = ''
for i in range(0, len(s)):
if s[i] >= 'a' and s[i] <= 'z' or s[i] >= '' and s[i] <= '' or s[i] >= 'A' and s[i] <= 'Z':
sTmp += s[i]
sTmp = sTmp.lower()
for i in range(0, len(sTmp)/2):
if sTmp[i] != sTmp[len(sTmp)-1-i]:
return False
return True