1. 程式人生 > 實用技巧 >680. 驗證迴文字串 Ⅱ

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;
}