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'.

分析:
先用两个指针: i, j 分别指向字符串的两端,然后一个往前移,一个往后移动。如果遇到不一样,则要么跳过i,要么跳过j,再不断比较。
 1 class Solution {
 2     public boolean validPalindrome(String s) {
 3         return validPalindrome(s, 0, s.length() - 1, false);
 4     }
 5     
 6     private boolean validPalindrome(String s, int start, int end, boolean mustMatch) {
 7         while (start < end) {
 8             if (s.charAt(start) != s.charAt(end)) {
 9                 if (mustMatch) return false;
10                 return validPalindrome(s, start + 1, end, true) || validPalindrome(s, start, end - 1, true);
11             }
12             start++;
13             end--;
14         }
15         return true;
16     }
17 }

 

posted @ 2020-02-04 01:16  北叶青藤  阅读(118)  评论(0编辑  收藏  举报