415. 有效回文串
中文
English
给定一个字符串,判断其是否为一个回文串。只考虑字母和数字,忽略大小写。
样例
样例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
解释: "amanaplanacanalpanama"
样例 2:
输入: "race a car"
输出: false
解释: "raceacar"
挑战
O(n) 时间复杂度,且不占用额外空间。
注意事项
你是否考虑过,字符串有可能是空字符串?这是面试过程中,面试官常常会问的问题。
在这个题目中,我们将空字符串判定为有效回文。
class Solution:
"""
@param s: A string
@return: Whether the string is a valid palindrome
"""
def isPalindrome(self, s):
# write your code here
l, r = 0, len(s)-1
def is_valid_char(c):
return 'a' <= c <= 'z' or 'A' <= c <= 'Z' \
or '0' <= c <= '9'
while l <= r:
while l <= r and not is_valid_char(s[l]):
l += 1
while l <= r and not is_valid_char(s[r]):
r -= 1
if l <= r:
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return True