2014.1.13 18:48
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.
Solution:
This problem doesn't involve maths or difficult algorithms, so it's the kind of easy problem to test if you're careful enough to solve it one-pass. Make NO mistake.
Time complexity is O(n), where n is the length of the string. Space complexity is O(1).
Accepted code:
1 // 1RE, 1AC, be more careful, could've 1AC~ 2 class Solution { 3 public: 4 bool isPalindrome(string s) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 int i, j, len; 8 9 len = s.length(); 10 if(len <= 0){ 11 return true; 12 } 13 14 char a, b; 15 16 i = 0; 17 j = len - 1; 18 while(i < j){ 19 if(s[i] >= 'a' && s[i] <= 'z'){ 20 a = s[i]; 21 }else if(s[i] >= '0' && s[i] <= '9'){ 22 a = s[i]; 23 }else if(s[i] >= 'A' && s[i] <= 'Z'){ 24 a = s[i] - 'A' + 'a'; 25 }else{ 26 ++i; 27 continue; 28 } 29 if(s[j] >= 'a' && s[j] <= 'z'){ 30 b = s[j]; 31 }else if(s[j] >= '0' && s[j] <= '9'){ 32 b = s[j]; 33 }else if(s[j] >= 'A' && s[j] <= 'Z'){ 34 b = s[j] - 'A' + 'a'; 35 }else{ 36 // 1RE here, wrong direction of $j 37 --j; 38 continue; 39 } 40 if(a == b){ 41 ++i; 42 --j; 43 }else{ 44 break; 45 } 46 } 47 48 return i >= j; 49 } 50 };