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

    Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

    Example 1:

    Input: "aba"
    Output: True

    Example 2:

    Input: "abca"
    Output: True
    Explanation: You could delete the character 'c'.

    Note:

    1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

    判断最多去掉一个字母后回文串是否有效。
    aba、abca、abc、acddcb
    判断回文串主要是利用双指针(left and right)和递归判断的方法。
    题目要求最多去除一个字母。
    首先找出回文首末位第一对不匹配的值。
    如果left == right,则说明这个字符串是奇数个,如“aba”这种类型。直接返回true。
    如果left < right,递归的判断后面的回文情况。并返回true。
    如果都不符合以上情况,返回false即可。

    class Solution {
    public:
        bool validPalindrome(string s) {
            int l = 0, r = s.size() - 1;
            while (l < r && s[l] == s[r]) {
                l++;
                r--;
            }
            if (l == r) {
                return true;
            }
            if (isPalindrome(s, l + 1, r) || isPalindrome(s, l, r - 1)) {
                return true;
            }
            return false;
        }
        bool isPalindrome(string s, int l, int r) {
            while (l < r) {
                if (s[l] == s[r]) {
                    l++;
                    r--;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }
    };
    // 112 ms

    接下来使用直观迭代的方法进行判断

    class Solution {
    public:
        bool validPalindrome(string s) {
            int left = 0, right = s.size() - 1;
            while (left < right) {
                if (s[left] == s[right]) {
                    left++;
                    right--;
                }
                else {
                    int tmpLeft = left, tmpRight = right - 1;
                    while (tmpLeft < tmpRight) {
                        if (s[tmpLeft] != s[tmpRight])
                            break;
                        tmpLeft++;
                        tmpRight--;
                        if (tmpLeft >= tmpRight)
                            return true;
                    }
                    left++;
                    while (left < right) {
                        if (s[left] != s[right])
                            return false;
                        left++;
                        right--;
                    }
                }
            }
            return true;
        }
    };
    // 145 ms
  • 相关阅读:
    HDU2897( 巴什博奕变形)
    HTML小知识点积累
    几种自己主动运行js代码的方式
    leetcode笔记:Contains Duplicate
    【Nutch基础教程之七】Nutch的2种执行模式:local及deploy
    为什么使用模板
    前端编程提高之旅(十)----表单验证插件与cookie插件
    【HDOJ 5399】Too Simple
    进程间通信之-信号signal--linux内核剖析(九)
    iOS类的合理设计,面向对象思想
  • 原文地址:https://www.cnblogs.com/immjc/p/7843221.html
Copyright © 2011-2022 走看看