125. Valid Palindrome(双指针)
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: str) -> bool: n = len(s) left, right = 0, n - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if left < right: if s[left].lower() != s[right].lower(): return False left, right = left + 1, right - 1 return True
class Solution { public: bool is_ok(char c) { return (('0' <= c && c <= '9') || ('a' <= c && c <='z') || ('A' <= c && c <='Z')); } bool isPalindrome(string s) { int l = 0, r = s.size() -1; while(l < r) { while(l < r && !is_ok(s[l]) ) l++; while(l < r && !is_ok(s[r]) ) r--; if (tolower(s[l]) != tolower(s[r])) return false; l++;r--; } return true; } };
1 class Solution: 2 def isPalindrome(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 if s=='': 8 return True 9 import re 10 x = re.sub('\W','',s).lower() 11 if x=='': 12 return True 13 if(len(x)%2!=0):#数 14 for i in range(int(len(x)/2)+1): 15 if(x[i]!=x[len(x)-i-1]): 16 return False 17 else: 18 for i in range(int(len(x)/2)+1): 19 if(x[i]!=x[len(x)-i-1]): 20 return False 21 return True 22