码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Valid Palindrome

时间:2018-01-05 01:16:22      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:determine   统一   class   ==   style   利用   body   lin   string   

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) {
        string pattern = pickAlphanumeric(s);
        int left = 0, right = pattern.size() - 1;
        while (left <= right) {
            if (pattern[left] == pattern[right]) {
                left++;
                right--;
            }
            else {
                break;
            }
        }
        if (left > right)
            return true;
        else
            return false;
    }
    
    string pickAlphanumeric(string& s)
    {
        string res;
        for (auto& c : s) {
            if (isalnum(c)) {
                if (isdigit(c))
                    res += c;
                else
                    res += tolower(c);
            }
        }
        return res;
    }
};
// 9 ms

 

[LeetCode] Valid Palindrome

标签:determine   统一   class   ==   style   利用   body   lin   string   

原文地址:https://www.cnblogs.com/immjc/p/8196553.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!