[LeetCode-125] Valid Palindrome
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.
从外往里比对,跳过无效索引,不匹配返回false即可,注意处理空串以及全忽略的case。
1 class Solution { 2 public: 3 // 4 // 0 not valid 5 // 1 valid 6 // 2 valid, but is caps 7 // 8 inline int check_char(int idx, const string& s) { 9 if ((s[idx] >= '0' && s[idx] <= '9') || (s[idx] >= 'a' && s[idx] <= 'z')) { 10 return 1; 11 } else if ((s[idx] >= 'A' && s[idx] <= 'Z')) { 12 return 2; 13 } 14 return 0; 15 } 16 17 bool isPalindrome(string s) { 18 // Start typing your C/C++ solution below 19 // DO NOT write int main() function 20 int idx_l = 0, idx_r = s.length() - 1, ret = 0; 21 char cl = 0, cr = 0; 22 while (idx_l < idx_r) { 23 while (idx_l < s.length() && (0 == (ret = (check_char(idx_l, s))))) { 24 ++idx_l; 25 } 26 if (idx_l < s.length()) { 27 cl = (1 == ret ? s[idx_l] : s[idx_l] - 'A' + 'a'); 28 } else { 29 cl = '\0'; 30 } 31 while (idx_r >= 0 && (0 == (ret = (check_char(idx_r, s))))) { 32 --idx_r; 33 } 34 if (idx_r >= 0) { 35 cr = (1 == ret ? s[idx_r] : s[idx_r] - 'A' + 'a'); 36 } else { 37 cr = '\0'; 38 } 39 if ((idx_l < idx_r) && cl != cr) { 40 return false; 41 } 42 ++idx_l; 43 --idx_r; 44 } 45 return true; 46 } 47 };
浙公网安备 33010602011771号