您的位置:首页 > 其它

LeetCode *** 125. Valid Palindrome

2016-04-10 20:48 260 查看
题目:

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.

分析:

因为题目没读明白以及自己粗心把j写成了i导致错了4次。唉,经常犯这些幼稚的错误。

代码:

class Solution {
public:
bool isPalindrome(string s) {

int i=0,j=s.length()-1;

while(i<j){

if((isalpha(s[i])||isdigit(s[i]))&&(isalpha(s[j])||isdigit(s[j]))){
if(isalpha(s[i]))s[i]=tolower(s[i]);
if(isalpha(s[j]))s[j]=tolower(s[j]);

if(s[i]!=s[j])return false;
else {i++;j--;}
}
else {
if(!(isalpha(s[i])||isdigit(s[i])))i++;
if(!(isalpha(s[j])||isdigit(s[j])))j--;
}
}

return true;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: