[LeetCode] 125. Valid Palindrome

来源:互联网 发布:淘宝如何开天猫店 编辑:程序博客网 时间:2024/06/05 04:25

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.

// naiveclass Solution {public:    bool isPalindrome(string s) {        int i = 0, j = (int)s.size() - 1;        while (i < j) {            if (!isalnum(s[i])) {                i++;                continue;            }            if (!isalnum(s[j])) {                j--;                continue;            }            if (tolower(s[i++]) != tolower(s[j--]))                return false;        }        return true;    }};
// much betterclass Solution {public:    bool isPalindrome(string s) {        for (int i = 0, j = (int)s.size() - 1; i < j; i++, j--) {            while (!isalnum(s[i]) && i < j) i++;            while (!isalnum(s[j]) && i < j) j--;            if (tolower(s[i]) != tolower(s[j]))                return false;        }        return true;    }};
原创粉丝点击