• [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
  • 相关阅读:
    计算机组成原理 04 认识各个硬件部件
    计算机组成原理 02 计算机的发展
    计算机组成原理 01 你好,计组
    蓝桥杯-2020-B组 &#183; 题解/解析(4/17)
    「HTML 5」1.HTML简介
    「易语言」主题颜色配置方案
    「易语言」那些年,我们经历的故事
    彻底解决Ubuntu中 “检测到系统程序错误”
    FFMPEG 的简单使用介绍 —— 合并音视频
    oh-my-zsh 中 agnoster主题 之 隐藏用户名信息
  • 原文地址:https://www.cnblogs.com/immjc/p/7843221.html
Copyright © 2020-2023  润新知