680. 验证回文字符串 Ⅱ

给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。

示例 1:

输入: "aba"
输出: True
示例 2:

输入: "abca"
输出: True
解释: 你可以删除c字符。
注意:

字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome-ii

思路:

判断字符串是否回文is so easy,但是这个题目就稍微有了一点小小的改变,不过也问题不大,这里的删除字符呢,就可以理解为跳过当前指针指到的值,左边跳一次看看OK不OK,不OK就再右边跳一次左边给他还原再看看OK不OK。

class Solution {
    public boolean validPalindrome(String s) {
        int l = 0;
        int r = s.length()-1;
        int contl = -1;
        int contr = -1;
        int index = 0;
        while(l<r){
            if(s.charAt(l) != s.charAt(r)){
                if(index == 0){
                    contl = l;
                    contr = r;
                    l++;
                    index++;
                    continue;
                }
                if(index == 1){
                    l = contl;
                    r = contr - 1;
                    index++;
                    continue;
                }
                if(index == 2){
                    return false;
                }
            }
            l++;
            r--;
        }
        return true;
    }
}

这样也是一样的道理

public boolean validPalindrome(String s) {
    for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
        if (s.charAt(i) != s.charAt(j)) {
            return isPalindrome(s, i, j - 1) || isPalindrome(s, i + 1, j);
        }
    }
    return true;
}

private boolean isPalindrome(String s, int i, int j) {
    while (i < j) {
        if (s.charAt(i++) != s.charAt(j--)) {
            return false;
        }
    }
    return true;
}
原文地址:https://www.cnblogs.com/zzxisgod/p/13335234.html