Leetcode: Valid Palindrome

来源:互联网 发布:淘宝运营公司靠谱嘛 编辑:程序博客网 时间:2024/06/05 19:01

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.

比较简单。

class Solution {public:    bool isPalindrome(string s) {        int len = s.size();        if (len == 0) {            return true;        }        --len;        for (int i = 0; i < len; ++i, --len) {            while (!isValidChar(s[i]) && i < len) {                ++i;            }            while (!isValidChar(s[len]) && i < len) {                --len;            }            if (i >= len) {                return true;            }            else if (tolower(s[i]) != tolower(s[len])) {                return false;            }        }                return true;    }        bool isValidChar(char ch) {        return (ch >= 'a' && ch <= 'z' ||                ch >= 'A' && ch <= 'Z' ||                ch >= '0' && ch <= '9');    }};

==================第二次=======================

class Solution {public:    bool isPalindrome(string s) {        if (s.empty()) {            return true;        }                int j = s.size() - 1;        for (int i = 0; i < j; ++i, --j) {            while (i < j && !isalnum(s[i])) {                ++i;            }            while (i < j && !isalnum(s[j])) {                --j;            }                        if (tolower(s[i]) != tolower(s[j])) {                return false;            }        }                return true;    }};


0 0
原创粉丝点击