1. 程式人生 > 其它 >【力扣 074】680. 驗證迴文字串 Ⅱ

【力扣 074】680. 驗證迴文字串 Ⅱ

680. 驗證迴文字串 Ⅱ

給定一個非空字串 s,最多刪除一個字元。判斷是否能成為迴文字串。

示例 1:

輸入: s = "aba"
輸出: true


示例 2:

輸入: s = "abca"
輸出: true
解釋: 你可以刪除c字元。


示例 3:

輸入: s = "abc"
輸出: false

來源:力扣(LeetCode)
連結:https://leetcode.cn/problems/valid-palindrome-ii
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

方法一:雙指標

class Solution {
public:
    bool validPalindrome(string s) 
    {
        int i = 0, j = s.size() -1;
        while(i <= j)
        {
            if(s[i] != s[j])
            {
                return isPalindrome(s, i+1, j) || isPalindrome(s, i, j-1);
            }
            else
            {
                ++i;
                --j;
            }
        }
        return true;
    }

    bool isPalindrome(string &s, int i, int j)
    {
        while(i <= j)
        {
            if(s[i++] != s[j--])
                return false;
        }
        return true;
    }
};

參考資料

1. 從兩側向中間找到不等的字元,刪除後判斷是否迴文