-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path125.py
45 lines (34 loc) · 1.19 KB
/
125.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def isPalindrome_1(self, s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
if not s[left].isalnum():
left += 1
elif not s[right].isalnum():
right -= 1
else:
if s[left].lower() != s[right].lower():
return False
else:
left += 1
right -= 1
return True
def isPalindrome(self, s: str) -> bool:
sgood = "".join([ch.lower() for ch in s if ch.isalnum()])
return sgood == sgood[::-1]
s = "A man, a plan, a canal: Panama"
# s = "race a car"
print(Solution().isPalindrome(s))