题目
代码
执行用时:60 ms, 在所有 Python3 提交中击败了26.62% 的用户
内存消耗:15.3 MB, 在所有 Python3 提交中击败了50.47% 的用户
通过测试用例:480 / 480
class Solution:
def isPalindrome(self, s: str) -> bool:
ans=""
for item in s:
num=ord(item)
if (num>=48 and num<=57) or (num>=97 and num<=122) or (num>=65 and num<=90):
ans+=item
ans=ans.lower()
return ans==ans[::-1]
【方法2】
执行用时:60 ms, 在所有 Python3 提交中击败了26.62% 的用户
内存消耗:15.3 MB, 在所有 Python3 提交中击败了50.47% 的用户
通过测试用例:480 / 480
class Solution:
def isPalindrome(self, s: str) -> bool:
ans=""
for item in s:
num=ord(item)
if (num>=48 and num<=57) or (num>=97 and num<=122):
ans+=item
elif (num>=65 and num<=90):
ans+=chr(num+32)
return ans==ans[::-1]
【方法3】双指针
执行用时:64 ms, 在所有 Python3 提交中击败了18.63% 的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了92.96% 的用户
通过测试用例:480 / 480
class Solution:
def isPalindrome(self, s: str) -> bool:
ans=True
left,right=0,len(s)-1
while left<right:
while left<right and not ((s[left]>='a' and s[left]<='z') or (s[left]>='A' and s[left]<='Z') or (s[left]>='0' and s[left]<='9')):left+=1
while left<right and not ((s[right]>='a' and s[right]<='z') or (s[right]>='A' and s[right]<='Z') or (s[right]>='0' and s[right]<='9')):right-=1
if s[left].lower()==s[right].lower():
left+=1
right-=1
else:
return False
return True
Python实现字符串回文判断:三种方法对比

本文探讨了三种Python方法判断字符串是否为回文:逐字符转换ASCII、字符类型过滤+转小写,以及双指针技巧。展示了它们的执行效率、内存消耗及通过测试情况,并详细解析了每种方法的工作原理。
622

被折叠的 条评论
为什么被折叠?



