LeetCode 125. Valid Palindrome

1. 题目描述

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.

2. 解题思路

这道题目很简单, 本来都不打算写了, 后来发现了, 大神代码中的一些亮点, 于是就来写一下了。
思路很简单, 两端扫描这个字符串, 如果他不是目标字符(字母和数字),pass.
然后比较两端的目标字符是否相等, 如果不等表明不是。

3. code

这是我们的代码, 里面造了很多轮子, 所以代码显得有些臃肿

class Solution {
public:
    bool isPalindrome(string s) {
        int start = 0, stop = s.size() - 1;
        while (start < stop){
            while (start < stop && !isAlphaNum(s[start]))
                start++;

            while (start < stop && !isAlphaNum(s[stop]))
                stop--;

            if (start > stop || !isEqual(s[start], s[stop]))
                return false;

            start++;
            stop--;
        }
        return true;
    }

private:
    inline bool isAlphaNum(char c){
        return isAlpha_low(c) || isAlpha_high(c) || isNum(c);
    }

    inline bool isNum(char c){
        return c >= '0' && c <= '9';
    }

    inline bool isAlpha_low(char c){
        return c >= 'a' && c <= 'z';
    }

    inline bool isAlpha_high(char c){
        return c >= 'A' && c <= 'Z';   
    }

    inline bool isEqual(char c1, char c2){
        if (isAlpha_high(c1))
            c1 = c1 - 'A' + 'a';
        if (isAlpha_high(c2))
            c2 = c2 - 'A' + 'a';

        return c1 == c2;
    }
};

4. 大神的解法

大神在这里用到了两个标准库函数 isalnum 和 toupper ,通过这两个库函数的应用, 大大节省了代码量, nice

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

你可能感兴趣的:(LeetCode,C++)