LeetCode *** 125. Valid Palindrome

来源:互联网 发布:网络剧大全 编辑:程序博客网 时间:2024/05/03 04:49

题目:

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;            }};

0 0