Problem Description:
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.
题目大意:
给定一个字符串,判断它是否是回文的。
Solutions:
这道题不难,只要对原始字符串进行适当的预处理之后(去掉标点符号)在判断是否是回文即可。
Code in C++:
class Solution {
public:
bool isPalindrome(string s) {
string nstr="";
for(int i = 0; i < s.length(); i++)
{
if(s[i]>='a'&&s[i]<='z')
nstr+=s[i];
else if(s[i]>='A'&&s[i]<='Z')
nstr+=(char)(s[i]-'A'+'a');
else if(s[i]>='0'&&s[i]<='9')
nstr+=s[i];
}
for(int i = 0;i<nstr.length();i++)
{
if(nstr[i]!=nstr[nstr.length()-1-i]) return false;
}
return true;
}
};
近期评论