首页 > 其他 > 详细

[LeetCode] Valid Palindrome

时间:2015-04-13 18:21:40      阅读:186      评论:0      收藏:0      [点我收藏+]

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.

 

Hide Tags
 Two Pointers String
 

 注意 extern int toupper(int c); 如果c为小写英文字母,则返回对应的大写字母;否则返回原来的值。

class Solution {
    public:
        bool isPalindrome(string s) {
            if(s.empty())
                return true;

            int idx1 = 0;
            int idx2 = s.size()-1;

            while(idx1 < idx2)
            {
                while(!isalnum(s[idx1]) && idx1 < idx2)
                {
                    idx1 ++;
                }

                while(!isalnum(s[idx2]) && idx1 < idx2)
                {
                    idx2 --;
                }

                if(idx1 >= idx2)
                    break;

                if(toupper(s[idx1]) == toupper(s[idx2]))
                {
                    idx1 ++;
                    idx2 --;
                }
                else
                    return false;
            }
            return true;

        }
};

 

使用transform 来更改字母的大小写

class Solution {
    public:
        bool isPalindrome(string s) {
            transform(s.begin(), s.end(), s.begin(), ::tolower);
            auto left = s.begin(), right = prev(s.end());
            while (left < right) {
                if (!::isalnum(*left)) ++left;
                else if (!::isalnum(*right)) --right;
                else if (*left != *right) return false;
            }
            return true;
        }
};

 

[LeetCode] Valid Palindrome

原文:http://www.cnblogs.com/diegodu/p/4422585.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!