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.
Two Pointers String 注意 extern
int
toupper
(
int
c);
如果c为小写英文字母,则返回对应的大写字母;否则返回原来的值。
class Solution { public: bool isPalindrome(string s) { if(s.empty()) return true; int idx1 = 0; int idx2 = s.size()-1; while(idx1 < idx2) { while(!isalnum(s[idx1]) && idx1 < idx2) { idx1 ++; } while(!isalnum(s[idx2]) && idx1 < idx2) { idx2 --; } if(idx1 >= idx2) break; if(toupper(s[idx1]) == toupper(s[idx2])) { idx1 ++; idx2 --; } else return false; } return true; } };
使用transform 来更改字母的大小写
class Solution { public: bool isPalindrome(string s) { transform(s.begin(), s.end(), s.begin(), ::tolower); auto left = s.begin(), right = prev(s.end()); while (left < right) { if (!::isalnum(*left)) ++left; else if (!::isalnum(*right)) --right; else if (*left != *right) return false; } return true; } };