问题描述:
好
times out:
1 class Solution(object): 2 def isPalindrome(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 j = len(s) - 1 8 i = 0 9 flag = True 10 while i != j and flag == True: 11 if s[i].isalnum() and s[j].isalnum(): 12 if s[i].lower() == s[j].lower(): 13 flag = True 14 else: 15 flag = False 16 if not s[i].isalnum() : 17 i += 1 18 if not s[j].isalnum(): 19 j -= 1 20 return flag 21
错误原因:相等的时候没有移动到下一个位置
1 class Solution(object): 2 def isPalindrome(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 j = len(s) - 1 8 i = 0 9 flag = True 10 while i < j : 11 if not s[i].isalnum() : 12 i += 1 13 continue 14 if not s[j].isalnum(): 15 j -= 1 16 continue 17 if s[i].lower() != s[j].lower(): 18 return False 19 i += 1 20 j -= 1 21 return flag
官方:
1 class Solution(object): 2 def isPalindrome(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 new_s = "".join([i for i in s if i.isalnum() or i.isalpha()]).lower() 8 return new_s == new_s[::-1]
正则表达式替换:
1 class Solution(object): 2 def isPalindrome(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 import re 8 s = re.sub('[^a-z0-9]','',s.lower()) 9 return s == s[::-1]
正则复习请看:http://www.runoob.com/python/python-reg-expressions.html
视频:https://www.bilibili.com/video/av7036891?from=search&seid=10436462392778970383
2018-09-12 19:51:17