415 · 有效回文串
Algorithms
中等
通过率
34%
题目题解笔记讨论排名
描述
给定一个字符串,判断其是否为一个回文串。只考虑字母和数字,忽略大小写。
你是否考虑过,字符串有可能是空字符串?这是面试过程中,面试官常常会问的问题。
在这个题目中,我们将空字符串判定为有效回文。
样例
样例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
解释: “amanaplanacanalpanama”
样例 2:
输入: “race a car”
输出: false
解释: “raceacar”
class Solution:
"""
@param s: A string
@return: Whether the string is a valid palindrome
"""
def isPalindrome(self, s):
# write your code here
s=s.lower()
s=list(s)
S=[]
for i in s:
if((i>="a" and i<="z") or (i>="0" and i<="9")):
S.append(i)
left=0
right=len(S)-1
while(1):
if(left>=right):
break
if(S[left]==S[right]):
left+=1
right-=1
else:
return False
return True