zoukankan      html  css  js  c++  java
  • [LeetCode] Valid Palindrome

    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
  • 相关阅读:
    非常可乐 HDU1495
    POJ3660 暑假集训-最短路H题floyd
    HDU2612 -暑假集训-搜索进阶N
    POJ-3126 暑假集训-搜索进阶F题
    HDU2544最短路模板,
    Alisha’s Party
    Milking Grid poj2185
    Period POJ
    Power Strings POJ
    Seek the Name, Seek the Fame (poj2752
  • 原文地址:https://www.cnblogs.com/immjc/p/8196553.html
Copyright © 2011-2022 走看看