[easy][String][two-pointer]125.
2017-11-26 本文已影响0人
小双2510
原题:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
思路:
两指针,从头尾同时开始找,比较是否相同。排除其他符号。
代码是
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
strlist = s.lower()
i = 0
j = len(s) - 1
letter_number = set(['1','2','3','4','5','6','7','8','9','0','a','b','c','d','e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'])
while i < j:
# print('----')
# print(i)
# print(strlist[i])
# print(j)
# print(strlist[j])
if strlist[i] in letter_number and strlist[j] in letter_number:
if strlist[i] != strlist[j]:
return False
else:
i += 1
j -= 1
elif strlist[i] in letter_number and strlist[j] not in letter_number:
j -= 1
else:
i += 1
return True
别人的代码用了一个API, isalnum()
def isPalindrome(self, s):
l, r = 0, len(s)-1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l <r and not s[r].isalnum():
r -= 1
if s[l].lower() != s[r].lower():
return False
l +=1; r -= 1
return True
插播两个找到所有字母的方法:
import string
wList = []
for word in string.lowercase:
wList.append(word)
print wList
#['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
# 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
# 'y', 'z']
list(map(chr, range(ord('a'), ord('z') + 1)))
#['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
[chr(x) for x in range(ord('a'), ord('z') + 1)]
#['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Screen Shot 2017-11-25 at 11.21.29 AM.png
Screen Shot 2017-11-25 at 11.26.51 AM.png