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.

 

只考虑数字和字母,忽略大小写,求是否是回文。一开始我的思路很简单,用一个新string存翻转后的字符串再和原来的比较

class Solution {

public:
   bool isPalindrome(string s) {
        if (s.empty())
            return true;
        string newS;
        for (char c : s)
        {
            if (isAlphaNumeric(c))
            {
                if ((c >= 'a') && (c <= 'z'))
                    c = c - 32;
    
                newS += c;
            }
        }
        string b = newS;
        reverse(newS.begin(), newS.end());
        if (newS == b)
            return true;
        else
            return false;
   }
    inline bool isAlphaNumeric(const char &c)
    {
        if ((c >= '0' && c <= '9') || ((c >= 'A') && (c<='Z')) || ((c>='a') && (c <= 'z')))
            return true;
        else
            return false;
    }

};

 觉得这样太慢了,就改用之前学到的两点法,一个从前往后,一个从后往前,不用再弄新数组。 

class Solution {
    //改用两点法
public:
    bool isPalindrome(string s) {
        if(s.empty())
            return true;
        int length = s.size();
        int i=0,j=length-1;
        while(i<j)
        {
            while(i<j && !isAlphaNumeric(s[i])) ++i;
            while(i<j && !isAlphaNumeric(s[j])) --j;
             

            if(i>=j) break;  
            if(s[i] != s[j])
                return false;
            
            ++i;
            --j;
        }
        return true;
    }
    inline bool isAlphaNumeric (char &c)
    {
        c = lowerCase(c);
         if ((c >= '0' && c <= '9') || ((c >= 'A') && (c<='Z')) || ((c>='a') && (c <= 'z')))
            return true;
        else 
            return false;
    }
    inline char lowerCase( char c) 
    {  
        if( c>='A' && c<='Z') return c + 'a' - 'A';  
        else return c;  
    } 

};

 

posted @ 2016-01-27 20:13  你好呵呵  阅读(271)  评论(0编辑  收藏  举报