给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
思路:双指针。
1 class Solution(object):
2 def isPalindrome(self, s):
3 """
4 :type s: str
5 :rtype: bool
6 """
7 if s == "":
8 return True
9 begin, end = 0, len(s) - 1
10 while begin < end:
11 if not s[begin].isalnum():
12 begin += 1
13 continue
14 elif not s[end].isalnum():
15 end -= 1
16 continue
17 elif s[begin].lower() != s[end].lower():
18 return False
19 begin += 1
20 end -= 1
21 return True
22
23 def isPalindrome2(self, s):
24 """
25 :type s: str
26 :rtype: bool
27 """
28 if s == "":
29 return True
30 list = []
31 # 记录list的长度
32 size = 0
33 # 遍历原字符串,将其中的字母转成小写格式放到list中
34 for i in range(len(s)):
35 if s[i].isalnum():
36 list.append(s[i].lower())
37 size += 1
38 else:
39 continue
40 i += 1
41
42 begin = 0
43 end = len(list) - 1
44 while begin < end:
45 if list[begin] != list[end]:
46 return False
47 begin += 1
48 end -= 1
49 return True
50
51
52 if __name__ == '__main__':
53 solution = Solution()
54 print(solution.isPalindrome2("A man, a plan, a canal: Panama"))