问题描述:
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;
int low = 0;
int high = s.size()-1;
while(low < high)
{
while(low < high && !isAlphanum(s[low]))
{//从前往后遍历,既不是字母又不数字,则略过
low++;
}
while(low < high && !isAlphanum(s[high]))
{//从后往前遍历,既不是字母又不数字,则略过
high--;
}//tolower()函数实现将大写转换为小写字母
if(tolower(s[low]) != tolower(s[high]))
{//如果对称位置的不相等
return false;
}
low++;
high--;
}
return true;
}
bool isAlphanum(char c)
{
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9');
}
};
本文介绍了如何通过编程方法判断一个字符串是否为回文字符串,同时考虑了忽略大小写及非字母数字字符的要求。具体实现包括自定义函数isAlphanum用于过滤非字母数字字符,并在主函数isPalindrome中使用该函数来判断字符串是否为回文。
422

被折叠的 条评论
为什么被折叠?



