[刷题防痴呆] 0680 - 验证回文字符串 II (Valid

2022-01-19  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/valid-palindrome-ii/

题目描述

680. 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'.


思路

关键点

代码

class Solution {
    public boolean validPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        int left = 0;
        int right = s.length() - 1;
        char[] sc = s.toCharArray();

        while (left < right) {
            if (sc[left] == sc[right]) {
                left++;
                right--;
            } else {
                return isSubValid(sc, left + 1, right) || isSubValid(sc, left, right - 1);
            }
        }

        return true;
    }

    private boolean isSubValid(char[] sc, int left, int right) {
        while (left < right) {
            if (sc[left] != sc[right]) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读