題目要求:
- 判斷一個(gè)字符串是否是回文横漏;
- 僅考慮字符串中字母和字符禀综,并且忽略大小寫截驮。
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
- 先去除字符串中的干擾項(xiàng)捌浩,僅保留字符和數(shù)字
- 再進(jìn)行首尾判斷
具體代碼如下:
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;
}