Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Notice
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.
Has you met this question in a real interview?
Example
"A man, a plan, a canal: Panama"is a palindrome.
"race a car"is not a palindrome.
Challenge
O (n) time without extra memory.
Leetcode on the original topic, please see my previous blog valid palindrome.
Solution One:
classSolution { Public: /** * @param s a string * @return Whether The string is a valid palindrome*/ BOOLIspalindrome (string&s) {intleft =0, right = S.size ()-1; while(Left <Right ) { if(!isalnum (S[left)) + +Left ; Else if(!isalnum (S[right]))--Right ; Else if((S[left] + +-'a') % +! = (S[right] + +-'a') % +)return false; Else { ++left; --Right ; } } return true; } BOOLIsalnum (Charc) {if(c >='a'&& C <='Z')return true; if(c >='A'&& C <='Z')return true; if(c >='0'&& C <='9')return true; return false; }};
Solution Two:
classSolution { Public: /** * @param s a string * @return Whether The string is a valid palindrome*/ BOOLIspalindrome (string&s) {intleft =0, right = S.size ()-1; while(Left <Right ) { if(!isalnum (S[left)) + +Left ; Else if(!isalnum (S[right]))--Right ; Else if((S[left] + +-'a') % +! = (S[right] + +-'a') % +)return false; Else { ++left; --Right ; } } return true; }};
[Lintcode] Valid palindrome Validating palindrome strings