您的位置:首页 > 编程语言 > Python开发

LeetCode刷题 (Python) | 125. Valid Palindrome

2016-01-30 20:34 746 查看

题目链接

https://oj.leetcode.com/problems/valid-palindrome/

心得

本身没什么难度,还是在于对原始字符串的处理。python的库实在是全面,用了两个函数就把原始字符串处理完了。需要注意的是,处理之后的字符串不要保存到string里,那样会超时,应该用list保存。具体原因不详,和python的实现有关,希望指点。

AC代码

class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
string = []
for c in s:
if c.isalnum():
string.append(c)
i, j = 0, len(string)-1
while i < j:
if string[i] != string[j]:
return False
i += 1
j -= 1
return True

if __name__ == "__main__":
solution = Solution()
print(solution.isPalindrome('aa'))


耗时88ms。

在讨论区看到一个更简洁的版本,也是88ms。

class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
cleanlist = [c for c in s.lower() if c.isalnum()]
return cleanlist == cleanlist[::-1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: