题目:
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) { if (s.size() == 0) return true; for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { while (!isalnum(s[i]) && i < s.size()) ++i; while (!isalnum(s[j]) && j > 0) --j; if (tolower(s[i]) != tolower(s[j]) && i < j) return false; } return true; } };