1. 程式人生 > >[LeetCode] 680. Valid Palindrome II

[LeetCode] 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.

題目大意

能否 最多刪除一個字元使原字串 變為 迴文串。

思路

雙指標i,j,左右對比字串元素,若某元素不同,那麼判斷 i,j-1 或 i+1,j 是否為 迴文串。

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