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.
Have you met this question in a real interview?
Yes
No
思路:首先把给定字符串里的是数字或者字母的存起来到temp字符串,然后对temp进行判断,思路还是很清晰的。如果一个字符是,那么我就应该将它添加到这个temp中,但是实现遇到了一点麻烦,主要是字符没办法直接添加到temp中。解决方案是:
char tmp[1];
tmp[0]=s[i]; //是数字或者字母
string result(tmp,1);
temp+=result;
实现代码如下:
class Solution { public: bool isPalindrome(string s) { string temp; for(int i=0;i<s.length();i++) { if(isalnum(s[i])){ if(s[i]>='A'&&s[i]<='Z') s[i]=s[i]+32; char tmp[1]; tmp[0] = s[i] ; string result(tmp,1); temp+=result; } } // cout<<temp<<endl; for(int i=0,j=temp.length()-1;i<j;i++,j--) { if(temp[i]!=temp[j]) return false; } return true; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。