Valid palindrome:https://leetcode.com/problems/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 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.
Analytical
Alphanumeric characters: alphabetic or numeric characters
The difficulty lies in:
1. Full space string should be judged as true
2. Letters are case insensitive
One algorithm is to remove all non-alphanumeric characters from the original string, insert it into a new string space, and then use the 2 pointer method to make a judgement based on the new string. The algorithm is simple to implement without extra consideration of the full space string, but takes up extra space.
Another algorithm is to use 2 pointers to both ends of the string, skipping when a non-alphanumeric character is encountered, and then doing the processing. For the full-space string, determine whether the left pointer will reach the end of the string. , the advantage is that it does not occupy extra space, and the time complexity is better than the first one (just iterate through an array).
Algorithm 1 implementation
Class Solution { Public:BOOL Ispalindrome(strings) {stringS2;inti =-1; while(++i < S.size ()) {if((S[i) <' A '|| S[i] >' Z ') && (S[i] <' A '|| S[i] >' Z ') && (S[i] <' 0 '|| S[i] >' 9 '))Continue;ElseS2 + = S[i]; } i =-1;intj = s2.size ();if(J = =0)return true;intInterval =' A '-' A '; while(++i <=--j) {if(! (S2[i] = = S2[j] | | s2[i]+interval = s2[j] | | s2[i]-interval = s2[j]))return false; }return true; }};
Algorithm 2 Implementation
Class Solution { Public:BOOL Ispalindrome(strings) {if(s.size () = =0)return true;inti =-1;intj = s.size ();intInterval =' A '-' A '; while(++i <=--j) { while((I < J) && (S[i] <' A '|| S[i] >' Z ') && (S[i] <' A '|| S[i] >' Z ') && (S[i] <' 0 '|| S[i] >' 9 ')) i++; while((I < J) && (S[j] <' A '|| S[J] >' Z ') && (S[j] <' A '|| S[J] >' Z ') && (S[j] <' 0 '|| S[J] >' 9 ')) j--;//Full space string if(i = = S.size ()-1)return true;if(S[i]! = s[j] && s[i]+interval! = s[j] && s[i]-interval! = S[j])return false; }return true; }};
Leetcode | Valid palindrome