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.
Seen this question in a real interview before?
Yes
分析:有效的回文
给定一个字符串,判断是否是回文,只考虑字母数字,并且忽略大小写。
这道题唯一难点就是处理大小写和非数字字母的字符。其实c++有现成的函数
isalnum() 判断字符是否为数字或者字母
toupper()将字母变成大写
tolower()将字母变成小写
代码:
class Solution {
public:
bool isPalindrome(string s) {
int first,last;
first = 0;
last = s.length()-1;
while(first<=last)
{
while(!(isalnum(s[first])) && first < last)
first++;
while(!(isalnum(s[last])) && first < last)
last--;
if(toupper(s[first])!=toupper(s[last]))
return false;
last--;
first++;
}
return true;
}
};