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.
判断回文是否有效。
思路:首先先将给定字符串中字母和数字挑选出来,并将大写字母统一改写成小写字母
然后利用二分查找判断回文
class Solution { public: bool isPalindrome(string s) { string pattern = pickAlphanumeric(s); int left = 0, right = pattern.size() - 1; while (left <= right) { if (pattern[left] == pattern[right]) { left++; right--; } else { break; } } if (left > right) return true; else return false; } string pickAlphanumeric(string& s) { string res; for (auto& c : s) { if (isalnum(c)) { if (isdigit(c)) res += c; else res += tolower(c); } } return res; } }; // 9 ms