More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/valid-palindrome-ii/java
Given a non-empty string s
, you may delete at most one character. Judge whether you can make it a palindrome.post
Example 1:ui
Input: "aba" Output: True
Example 2:spa
Input: "abca" Output: True Explanation: You could delete the character 'c'.
1.Make use of two pointers.code
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; } private boolean isPalindrome(String s, int i, int j){ while(i < j){ if(s.charAt(i++) != s.charAt(j--)) return false; } return true; }
Time complexity : O(n)
htm
Space complexity : O(1)blog
1. It's important to learn and make use of the method isPalindrome()
ip
More:【目錄】LeetCode Java實現leetcode