Valid Palindrome

来源:互联网 发布:asp.net php 编辑:程序博客网 时间:2024/04/27 08:58

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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function                if(s.length() == 0) return true;                int i = 0,j = s.length() - 1;                while(i < j)        {            while(!isalnum(s[i]) && i < j ) i++;            if(i==j) return true;                        while(!isalnum(s[j])) j--;            if(i>=j) return true;                        if(tolower(s[i++]) != tolower(s[j--])) return false;        }        return true;    }};

52 milli secs



原创粉丝点击