LeetCode Valid Palindrome

class Solution {

public:

    bool isPalindrome(string s) {

        int len = s.length();

        //if (len < 1) return true;

        int p = -1, q = len;

        while (true) {

            char a, b;

            while (++p < len && !(a = check2lower(s[p])) );

            while (--q > -1 && !(b = check2lower(s[q])) );

            if (p >= q) return true;

            if (a != b) {

                return false;

            }

        }

        return true;

    }

    

    char check2lower(char ch) {

        if (ch <= '9' && ch >= '0') return ch;

        if (ch <= 'z' && ch >= 'a') return ch;

        if (ch <= 'Z' && ch >= 'A') return ch + 'a' - 'A';

        return '\0';

    }

};

跟快排的结构有点类似

 

第二轮:

 

class Solution {

public:

    bool isChar(char ch) {

        return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9';

    }

    

    bool cmpChar(char a, char b) {

        if (a >= 'a') {

            a-=32;

        }

        if (b >= 'a') {

            b-=32;

        }

        return a == b;

    }



    bool isPalindrome(string s) {

        int len = s.size();

        int p = 0;

        int q = len-1;

        while (p<q) {

            while(!isChar(s[p]) && p < q) p++;

            while(!isChar(s[q]) && p < q) q--;

            if (p >= q) break;

            if (cmpChar(s[p], s[q])) {

                p++, q--;

            } else {

                return false;

            }

        }

        return true;

    }

};

  

第三轮:

class Solution {

public:

    bool isPalindrome(string s) {

        int len = s.size();

        int p = 0;

        int q = len - 1;

        while (p < q) {

            while (p < len && !isAlphanumeric(s[p])) {

                p++;

            }

            while (q > 0 && !isAlphanumeric(s[q])) {

                q--;

            }

            if (p >= q) {

                return true;

            }

            if (toLowerCase(s[p]) != toLowerCase(s[q])) {

                return false;

            }

            p++, q--;

        }

        return true;

    }

    char toLowerCase(char ch) {

        if (ch >= 'a') {

            ch-= 'a' - 'A';

        }

        return ch;

    }

    bool isAlphanumeric(char ch) {

        if (ch >= 'a' && ch <= 'z' 

            || ch >= 'A' && ch <= 'Z'

            || ch >= '0' && ch <= '9') {

            return true;

        }

        return false;

    }

};

 

你可能感兴趣的:(LeetCode)