題目
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.
分析
題目給出一個字符串罢艾,判斷該字符串是不是回文推励,但是要忽略除了數(shù)字字母以外的任何字符妖混,并且不區(qū)分大小寫熔脂,而且有空字符串的情況出現(xiàn),空字符串判定為真
解題的想法就是沙咏,先得到干凈的字符串(只有字母數(shù)字),然后首位開始依次向中間移動開始判斷
代碼
class Solution {
public:
bool isPalindrome(string s) {
//判斷字符串是不是為空,為空直接true
if(s.empty())
return true;
//去除除了字母和數(shù)字以外的所有字符
string str = clear(s);
for (int i=0,j=str.length()-1;i<j;i++,j--){
if (str[i]!=str[j]){
return false;
}
}
return true;
}
//清理函數(shù)扒接,將字符串去除除了字母和數(shù)字意外的字符,并將全部字符轉為小寫
string clear(string s){
string str = "";
char c;
for(int i=0;i<s.length();i++){
c = s[i];
if (c>='A'&&c<='Z' || c>='a'&&c<='z' || c>='0'&&c<='9'){
if (c>='A'&c<='Z')
str+=c+32;
else
str+=c;
}
}
return str;
}
};