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:
Are you consider that the string might is empty? This was a good question to ask during a interview.
For the purpose of this problem, we define empty string as valid palindrome.
Tags: Pointers String
Solution 1:my Weak suolution, create a new string to input only alphanumeric
BOOLIspalindrome (strings) {if(S.empty ())return true; string:: Iterator Iter1=s.begin (), iter2=S.end (); stringNews; for(; iter1!=iter2;iter1++){ if(Isalnum (*iter1)) News.push_back (ToLower (*iter1)); } if(news.size () = =1)return true; for(intI=0, J=news.size ()-1; i<j;i++,j--){ if(News[i]!=news[j])return false; } return true;}
Solution 2:clean Code
BOOLIspalindrome (strings) { for(inti =0, j = s.size ()-1; I < J; i++, j--) {//Move 2 pointers from each end until they collide while(Isalnum (s[i]) = =false&& i < j) i++;//Increment left pointer if not alphanumeric while(Isalnum (s[j]) = =false&& i < j) j--;//decrement right pointer if no alphanumeric if(ToUpper (s[i])! = ToUpper (S[j]))return false;//Exit and return error if not match } return true; }
"Leetcode" 125-valid palindrome