[String]680. Valid Palindrome II

2017-10-22  本文已影响0人  Reflection_

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

第一次:
想法是当第一次遇到不同,则比较左下一位是否与右当前一致,一致则左+1;否则比较右+1位和左当前;都不一致则返回false。
458 / 460 test cases passed.
失败于"cuppucu" 这样的例子,删左删右结果不同

class Solution {
    public boolean validPalindrome(String s) {
        boolean delete = false;
        int len = s.length();
        if(len <= 2 && len >= 0) return true;
        
        for(int i =0, j = len-1;i<j;i++,j--){
            if(s.charAt(i) != s.charAt(j)){
                if(!delete){
                    delete = true;
                    if(s.charAt(i+1) == s.charAt(j)){
                        i++;
                    }else if(s.charAt(i) == s.charAt(j-1)){
                        j--;
                    }else return false;
                }else{
                    return false;
                }
            }
        }
        return true;
    }
}

第二次尝试:
460 / 460 test cases passed.
Runtime: 349 ms
效率非常低下

class Solution {
    public boolean validPalindrome(String s) {
        boolean delete = false;
        int len = s.length();
        if(len <= 2 && len >= 0) return true;
                   

        for(int i =0, j = len-1;i<j;i++,j--){
            if(s.charAt(i) != s.charAt(j)){
                    if(s.charAt(i+1) == s.charAt(j)){ //左删一位可以的情况下,先尝试这种办法
                        int i2 = i+1, j2 = j;
                        while(i2 < j2){
                            if(s.charAt(i2) != s.charAt(j2)) break;
                            i2++;j2--;
                            if(i2>=j2) return true;
                        }
                    }else{//左删不可以,或者左删尝试失败时 尝试右删,右删再失败就失败
                        j = j-1;
                        while(i < j){
                            if(s.charAt(i) != s.charAt(j)) return false;
                            i++;j--;
                        }
                    }
            }
        }
        return true;      
    }
}

分享一下优秀版:
所以这么简单的道理,到底为什么自己想的那么复杂呢?

class Solution {
    public boolean validPalindrome(String s) {
        int l = -1, r = s.length();
        while (++l < --r) {
            if (s.charAt(l) != s.charAt(r)) return isPalindromic(s, l, r+1) || isPalindromic(s, l-1, r);//左删or右删
        }
        return true;
    }
    private boolean isPalindromic(String s, int l, int r) {
        while (++l < --r) {
            if (s.charAt(l) != s.charAt(r)) return false;
        }
        return true;
    }
}
上一篇下一篇

猜你喜欢

热点阅读