forked from tcandzq/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidPalindrome.py
More file actions
46 lines (36 loc) · 1 KB
/
ValidPalindrome.py
File metadata and controls
46 lines (36 loc) · 1 KB
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
46
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/18 23:11
# @Author : tc
# @File : ValidPalindrome.py
"""
题号 125 验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
中心扩展法,从中间位置向两边扩散
"""
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
s = ''.join([x for x in s if x.isalpha() or x.isdigit()])
if not s:
return True
i = 0
j = len(s) - 1
if not s:
return False
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
if __name__ == '__main__':
solution = Solution()
print(solution.isPalindrome('race a car'))