给定一个字符串,判断是否为回文字符串,只需考虑字母和数字,忽略空格。
注意:空字符串算作回文字符串。
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.
分析:
简单的模拟思路
1)重新提取字符和数字(也是字符)
2)遍历一半长度,检查是否不匹配
class Solution {
public:
//1)重新提取字符和数字(也是字符)
string getAlpha(string str)
{
string result;
for(int i=0;i<str.size();i++)
{
if(str[i]<='z'&&str[i]>='a'||str[i]<='9'&&str[i]>='0')
result.push_back(str[i]);
if(str[i]<='Z'&&str[i]>='A')//转化为小写字母
result.push_back(str[i]+32);
}
return result;
}
bool isPalindrome(string s) {
if(s.empty())
return true;
string result= getAlpha(s);
for(int i=0;i<result.size()/2;i++)//2)遍历一半长度,检查是否不匹配
{
if(result[i]!=result[result.size()-1-i])
return false;
}
return true;
}
};
以下参考讨论区
基本思路:两个指针扫描数组,即一头一尾两个指针,向中间移动。
题目要求,判断一字符串,是否为符号,只考虑字母和数字,并且忽略大小写。
用 isalnum函数,判断是否为字母和数字;
用 tolower函数,将字母都作转换小写字母
class Solution {
public:
bool isPalindrome(string str) {
int start=0, end=str.length()-1;
while(start<end)
{
if (!isalnum(str[start])) //此函数判断字符变量str[i]是否为字母或数字,若是则返回非零,否则返回零。
start++;
else if (!isalnum(str[end]))
end--;
else if (tolower(str[start++])!=tolower(str[end--]))
return false;
}
return true;
}
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50583216
原作者博客:http://blog.csdn.net/ebowtang