【LeetCode】125 - Valid Palindrome

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.

Tags :Two Pointers String

Solution 1 : my weak suolution, create a new string to input only alphanumeric
bool isPalindrome(string s) {    
    if(s.empty())return true;
    string::iterator iter1=s.begin(),iter2=s.end();
    string news;
    for(;iter1!=iter2;iter1++){
        if(isalnum(*iter1))
            news.push_back(tolower(*iter1));
    }
    if(news.size()==1)return true;
    for(int i=0,j=news.size()-1;i<j;i++,j--){
        if(news[i]!=news[j])return false;
    }
    return true;
}

 

Solution 2: clean code

    bool isPalindrome(string s) {
        for (int i = 0, j = s.size() - 1; i < j; i++, j--) { // Move 2 pointers from each end until they collide
            while (isalnum(s[i]) == false && i < j) i++; // Increment left pointer if not alphanumeric
            while (isalnum(s[j]) == false && i < j) j--; // Decrement right pointer if no alphanumeric
            if (toupper(s[i]) != toupper(s[j])) return false; // Exit and return error if not match
        }
    
        return true;
    }

 

 
posted @ 2015-09-10 20:41  irun  阅读(165)  评论(0编辑  收藏  举报