【Lintcode】891. Valid Palindrome II

題目地址:

https://www.lintcode.com/problem/valid-palindrome-ii/description

給定一個字符串,如果其本身或者其刪去一個字符就能成爲迴文串,則返回true,否則返回false。只需用對撞雙指針依次判斷字符是否相等,如果不等,就嘗試將左指針右移一格或者右指針左移一格繼續判斷即可。代碼如下:

public class Solution {
    /**
     * @param s: a string
     * @return boolean: whether you can make s a palindrome by deleting at most one character
     */
    public boolean validPalindrome(String s) {
        // Write your code here
        if (s == null || s.isEmpty()) {
            return true;
        }
        
        int i = 0, j = s.length() - 1;
        while (i < j) {
            if (s.charAt(i) == s.charAt(j)) {
                i++;
                j--;
            } else {
                return isPalindrome(s, i + 1, j) || isPalindrome(s, i, j - 1);
            }
        }
        
        return true;
    }
    
    // 判斷s[i,...,j]是否爲迴文串
    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;
    }
}

時間複雜度O(n)O(n),空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章