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:

  1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
Accepted
61,989
Submissions
183,954
 
 
class Solution {
    public boolean validPalindrome(String s) {
        int i = -1, j = s.length();
        while(++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;
        }
        return true;
    }
}

猜你喜欢

转载自www.cnblogs.com/Roni-i/p/10427154.html