680. Valid Palindrome II

Easy
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'.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

這道題注意下時間復雜度,第一種做法tle了:大神給的提示:
一般做題多了會有感覺,比如

n^3 ---->10^2- 10^3
n^2 ---->10^3- 10^4,
nlogn ----> 10^4- 10^6,
n ---->10^6- 10^7

image.png
image.png
class Solution {
    //Construct all possible String that deleted one character from original string s
    //then find out if there exist one palindrome
    public boolean validPalindrome(String s) {
        if (s == null || s.length() == 0){
            return true;
        }    
        int l = 0;
        int r = s.length() - 1;
        int count1 = 0;
        int count2 = 0;
        while (l < r){
            if (s.charAt(l) != s.charAt(r)){
                l++;
                count1++;
            } else {
                l++;
                r--;
            }
        }
        l = 0;
        r = s.length() - 1;
        while (l < r){
            if (s.charAt(l) != s.charAt(r)){
                r--;
                count2++;
            } else {
                l++;
                r--;
            }
        }
        return (count1 < 2 || count2 < 2);
    }
}

A better way:
這種做法直接用Two Pointers, 遇到charAt(l) != chatAt(r)的時候,再看看分別去掉左邊當前char的字符串和去掉右邊當前char字符串的是不是回文就行了。

class Solution {
    //Construct all possible String that deleted one character from original string s
    //then find out if there exist one palindrome
    public boolean validPalindrome(String s) {
        if (s == null || s.length() == 0){
            return true;
        }    
        int l = 0;
        int r = s.length() - 1;
        while (l < r){
            if (s.charAt(l) != s.charAt(r)){
                return (isValidPalindrome(s, l + 1, r) || isValidPalindrome(s, l, r - 1));
            } else {
                l++;
                r--;
            }
        }
        return true;
    }
    
    public boolean isValidPalindrome(String s, int l, int r){
        while (l < r){
            if (s.charAt(l) != s.charAt(r)){
                return false;
            } else {
                l++;
                r--;
            }
        }
        return true;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容