经典中的经典题。奇怪的是like的人不多。
先是老老实实的写了个list,把奇奇怪怪的字符给去掉了。
果然很慢。但是程序可读性杠杆的。
class Solution:
def isPalindrome(self, s: str) -> bool:
def isLower(c):
if ord(c) >= ord('a') and ord(c) <= ord('z'):
return True
return False
def isCapital(c):
if ord(c) >= ord('A') and ord(c) <= ord('Z'):
return True
return False
def isNumeric(c):
if ord(c) >= ord('0') and ord(c) <= ord('9'):
return True
return False
# first only save the 'good' lowercase chars -- alphanumeric
clean_list = []
for i in range(len(s)):
if isNumeric(s[i]):
clean_list.append(s[i])
elif isCapital(s[i]):
clean_list.append(s[i].lower())
elif isLower(s[i]):
clean_list.append(s[i])
# then from the middle, check wheher they are symmetric
if len(clean_list) == 0:
return True
i=0
j=len(clean_list)-1
while i<j:
if clean_list[i] != clean_list[j]:
return False
i += 1
j -= 1
return True
改进下,去掉clean_list,直接左右比较,还是太慢。咋回事?
估计是Python3行数太多的缘故。
class Solution:
def isPalindrome(self, s: str) -> bool:
def isLower(c):
if ord(c) >= ord('a') and ord(c) <= ord('z'):
return True
return False
def isCapital(c):
if ord(c) >= ord('A') and ord(c) <= ord('Z'):
return True
return False
def isNumeric(c):
if ord(c) >= ord('0') and ord(c) <= ord('9'):
return True
return False
def getNextLeft(s, i):
while i<len(s):
if isLower(s[i]) or isNumeric(s[i]):
return (s[i],i+1)
elif isCapital(s[i]):
return (s[i].lower(), i+1)
i+=1
return(None, i)
def getNextRight(s, j):
while j>=0:
if isLower(s[j]) or isNumeric(s[j]):
return (s[j],j-1)
elif isCapital(s[j]):
return (s[j].lower(), j-1)
j-=1
return(None, j)
# then from the middle, check wheher they are symmetric
if len(s) == 0:
return True
i=0
j=len(s)-1
while i<j:
a,i = getNextLeft(s, i)
b,j = getNextRight(s, j)
if a != b:
return False
return True
搞了半天,Python3有个叫isalnum()的函数,一下就把一大堆自定义函数删了。
class Solution:
def isPalindrome(self, s: str) -> bool:
# then from the middle, check wheher they are symmetric
if len(s) == 0:
return True
i=0
j=len(s)-1
while i<j:
if s[i].isalnum() and s[j].isalnum():
if s[i].lower() != s[j].lower():
return False
i+=1
j-=1
elif not s[i].isalnum():
i+=1
elif not s[j].isalnum():
j-=1
return True
Python版的充分利用了Python3的函数,比如构造string,string reverse等。
class Solution:
def isPalindrome(self, s: str) -> bool:
# then from the middle, check wheher they are symmetric
if len(s) == 0:
return True
clean = ''.join(char.lower() for char in s if char.isalnum())
#clean = clean.lower()
if clean[::-1] != clean:
return False
return True