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.
思路:只把大小写字母和数字留下,用stl反置一下再对比是否相同。
另外有个函数可以检测是否是字母和数字。不过在这题里不是很合适,因为有大小写的缘故。
int isalnum ( int c )
参考代码:
class Solution {
public:
bool isPalindrome(string s) {
if(s.empty())
return true;
string str;
for(int i = 0; i <s.length(); ++i)
{
if((s[i]>='a'&&s[i]<='z') || (s[i]>='0'&&s[i]<='9'))
str+=s[i];
else if(s[i]>='A'&&s[i]<='Z')
str+=s[i]-'A'+'a';
}
string rev_str = str;
reverse(rev_str.begin(), rev_str.end());
return rev_str == str;
}
};
//SECOND TRIALclass Solution {public :bool isPalindrome ( string s ) {if ( s . empty ())return true ;int cnt = 0 ;for ( int i = 0 ; i < s . length (); ++ i ){if (( s [ i ] >= '0' && s [ i ] <= '9' ) || ( s [ i ] >= 'a' && s [ i ] <= 'z' ))s [ cnt ++ ] = s [ i ];else if ( s [ i ] >= 'A' && s [ i ] <= 'Z' )s [ cnt ++ ] = s [ i ] + 'a' - 'A' ;}s = s . substr ( 0 , cnt );string revs ( s . rbegin (), s . rend ());return revs == s ;}};