题目要求:
- 判断一个字符串是否是回文;
- 仅考虑字符串中字母和字符,并且忽略大小写。
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
- 先去除字符串中的干扰项,仅保留字符和数字
- 再进行首尾判断
具体代码如下:
bool isPalindrome(string s) {
s = removeNoise(s);
for(int i = 0;i<s.size()/2;i++){
if(s[i] != s[s.size()-i-1]){
return false;
}
}
return true;
}
string removeNoise(const string& s){
string d;
for(int i= 0;i<s.size();i++){
if(::isalpha(s[i]) || ::isdigit(s[i])){
d.push_back(::tolower(s[i]));
}
}
return d;
}