题目大意:
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.
意思就是:
给定一个字符串,判断该字符串是否是回文。仅考虑字母和数字,不许考虑空格,逗号等字符。
思路:
一重循环即可解决。设置两个位置变量i和j,i从字符串开头开始往后走,j从字符串结尾开始往前走。遇到非字母和非数字,则不考虑,继续走;遇到字母或数字则进行判断,直到判断完整个字符串。
代码如下:
class Solution{
public:
bool isPalindrome(string s){
int i = 0, j = s.length()-1;
while(i<j){
if(!isvalid(s[i])){
i++;
continue;
}
if(!isvalid(s[j])){
j--;
continue;
}
if(isdigit(s[i])){
if(s[i] == s[j]){
i++;
j--;
}
else{
return false;
}
}
else if(isalpha(s[i])){
if(tolower(s[i]) == tolower(s[j])){
i++;
j--;
}
else{
return false;
}
}
}
return true;
}
bool isvalid(char s){
if(isalnum(s)){
return true;
}
else{
return false;
}
}
};
注:string中处理字符的一些有用函数。头文件为:cctype
isalnum(c) 如果c是字母或数字,则为true。
isalpha(c) 如果c是字母,则为true。
isdigit(c) 如果c是数字,则为true。
tolower(c) 如果c是大写字母,则返回其小写字母,否则直接返回c。
toupper(c) 如果c是小写字母,则返回其大写字母,否则直接返回c。
isupper(c) 如果c是大写字母,则返回true。
islower(c) 如果c是小写字母,则返回true。