LeetCode 125: Valid Palindrome

来源:互联网 发布:flash动画设置软件 编辑:程序博客网 时间:2024/04/28 18:29

Difficulty: 2

Frequency: 5


Problem:

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.


Solution:

class Solution {public:    bool isPalindrome(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int i_forward = 0, i_backward = s.size() - 1;        while(i_forward<i_backward&&i_forward<s.size()&&i_backward>0)        {            while(!((s[i_forward]>='a'&&s[i_forward]<='z')||(s[i_forward]>='A'&&s[i_forward]<='Z')||(s[i_forward]>='0'&&s[i_forward]<='9'))&&i_forward<i_backward)                ++i_forward;                            while(!((s[i_backward]>='a'&&s[i_backward]<='z')||(s[i_backward]>='A'&&s[i_backward]<='Z')||(s[i_backward]>='0'&&s[i_backward]<='9'))&&i_backward>i_forward)                --i_backward;                            if (s[i_backward]>='a'&&s[i_backward]<='z')                s[i_backward]-=32;                            if (s[i_forward]>='a'&&s[i_forward]<='z')                s[i_forward]-=32;                            if (s[i_backward]!=s[i_forward])                return false;                            ++i_forward;            --i_backward;        }        return true;    }};


原创粉丝点击