zoukankan      html  css  js  c++  java
  • [LeetCode] 680. Valid Palindrome II 验证回文字符串 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.

    125. Valid Palindrome 的拓展,给定一个非空字符串,最多可删除1个字符,判断是否可以变成回文。

    解法:还是从首尾两边开始比较,如果匹配就移动指针继续比较。当遇到不匹配的时候,删除左边的字符或者右边的字符,只要有一种能匹配就继续。

    Python:

    class Solution(object):
        def validPalindrome(self, s):
            """
            :type s: str
            :rtype: bool
            """
            def validPalindrome(s, left, right):
                while left < right:
                    if s[left] != s[right]:
                        return False
                    left, right = left+1, right-1
                return True
            
            left, right = 0, len(s)-1
            while left < right:
                if s[left] != s[right]:
                    return validPalindrome(s, left, right-1) or validPalindrome(s, left+1, right)
                left, right = left+1, right-1
            return True
    

    C++:

    class Solution {
    public:
        bool validPalindrome(string s) {
            int left = 0, right = s.length() - 1;
            while (left < right) {
                if (s[left] != s[right]) {
                    return validPalindrome(s, left, right - 1) || validPalindrome(s, left + 1, right);
                }
                ++left, --right;
            }
            return true;
        }
    
    private:
        bool validPalindrome(const string& s, int left, int right) {
            while (left < right) {
                if (s[left] != s[right]) {
                    return false;
                }
                ++left, --right;
            }
            return true;
        }
    };

    类似题目:

    [LeetCode] 125. Valid Palindrome 验证回文字符串

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    QString::toStdString() crashes
    Consolas 字体
    Mesh BRep Shapes
    PyOpenCL库安装
    全国精确到乡镇的行政边界、路网水系建筑poi等矢量shp免费下载
    DEM数据(ASTER GDEM|SRTM|GLS2005|ALOS DEM)下载
    IDL基础
    辐射定标与FLAASH大气校正
    Circos绘图—基础
    R-散点密度图
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8628189.html
Copyright © 2011-2022 走看看