一.题目
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama" 输出: true
示例 2:
输入: "race a car" 输出: false
二.思路及代码
1> 一串字符串先整理成无符号全小写的形式,然后切一半前后比较(因为最大下标比长度小1,所以如果长度为偶数,前一半的下标就从 0 取到 floor((len(s) - 1)/2),后一半和前一半长度一样从倒数第一开始取)
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
new_s = ''
for i in s:
if i.isdigit() or i.islower():
new_s = new_s + i
elif i.isupper():
new_s = new_s + i.lower()
if new_s == '':
return True
else:
i = 0
j = len(new_s) - 1
while i <= math.floor((len(new_s) - 1)/2):
if new_s[i] == new_s[j]:
i += 1
j -= 1
else:
return False
return True
class Solution:
def isPalindrome(self, s):
"""
Using traditional while loop for processing
:type s: str
:rtype: bool
"""
if len(s) == 0 or len(s) == 1:
return True
# len(s) > 0
i = 0
j = len(s)-1
sen = s.lower()
while i <= j:
while i < len(s) and not (sen[i].isalnum()):
i+=1
while j > -1 and not (sen[j].isalnum()):
j-=1
if i <= j:
if sen[i] != sen[j]:
return False
else:
i+=1
j-=1
return True
2> 利用python的method
上一个方法的用时比较长,这道题简直是为python里str 的 method量身定做的。
1) str.isalnum()
# by myself
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# Method 2
s = s.lower()
new_s = ''
for i in s:
if i.isalnum():
new_s = new_s + i
if new_s == new_s[::-1]:
return True
else:
return False
# by example
class Solution:
def isPalindrome(self, s):
"""
Using python library for processing
:type s: str
:rtype: bool
"""
if len(s) == 0 or len(s) == 1:
return True
# len(s) > 0
sen = [item for item in s.lower() if item.isalnum()]
return sen == sen[::-1]
2)str.replace()
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s=s.lower()
for punc in string.punctuation:
s = s.replace(punc,'')
s = s.replace(' ','')
if s[::-1]==s:
return True
else: return False
3) str.join(seq) --其中str为seq间的间隔,通常可以用"", ","等,下面的例子就用了""
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s1 = []
for i in s:
if i.isalpha() or i.isalnum():
s1.append(i)
s = "".join(s1)
s = s.lower()
d = s[::-1]
if s == d:
return True
else:
return False