LeetCode #680 Valid Palindrome II 驗證回文字符串 Ⅱ

680 Valid Palindrome II 驗證回文字符串 Ⅱ

Description:
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example:

Example 1:

Input: "aba"
Output: True

Example 2:

Input: "abca"
Output: True
Explanation: You could delete the character 'c'.

Note:

The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

題目描述:
給定一個非空字符串 s,最多刪除一個字符。判斷是否能成為回文字符串。

示例 :

示例 1:

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

輸入: "abca"
輸出: True
解釋: 你可以刪除c字符。

注意:

字符串只包含從 a-z 的小寫字母。字符串的最大長度是50000。

思路:

判斷回文用雙指針, 如果找到第一次不一樣的字符, 可以左指針加一個字符或者右指針減一個字符再判斷一次
時間復雜度O(n), 空間復雜度O(1)

代碼:
C++:

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

Java:

class Solution {
    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 + 1, j) || isPalindrome(s, i, j - 1);
        return true;
    }
    
    private boolean isPalindrome(String s, int i, int j) {
        while (i < j) {
            if (s.charAt(i) != s.charAt(j)) return false;
            i++;
            j--;
        }  
        return true;
    }
}

Python:

class Solution:
    def validPalindrome(self, s: str) -> bool:
        if s == s[::-1]:
            return True
        l, r = 0, len(s) - 1
        while l < r:
            if s[l] == s[r]:
                l, r = l + 1, r - 1
            else:
                a, b = s[l + 1:r + 1], s[l:r]
                return a == a[::-1] or b == b[::-1]
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容