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

最多删掉一个字符,判断这个字符串是不是回文串。

C++(145ms):
 1 class Solution {
 2 public:
 3     bool valid(string& s, int i, int j, int d) { 
 4         if (i >= j)
 5             return true ;
 6         if (s[i] == s[j])
 7             return valid(s,i+1,j-1,d) ;
 8         else
 9             return d > 0 &&(valid(s,i+1,j,d-1) || valid(s,i,j-1,d-1));
10     }
11     
12     bool validPalindrome(string s) {
13         return valid(s,0,s.length()-1,1) ;
14     }
15 
16 };

Java(57ms):

 1 class Solution {
 2     public boolean validPalindrome(String s) {
 3         int left = 0 ;
 4         int right = s.length()-1 ;
 5         while(left <= right){
 6             if (s.charAt(left) != s.charAt(right)){
 7                 return valid(s,left+1,right) || valid(s,left,right-1);
 8             }
 9             left++ ;
10             right-- ;
11         }
12         return true ;
13     }
14     
15     public boolean valid(String s,int left , int right) {
16         while(left <= right){
17             if (s.charAt(left) == s.charAt(right)){
18                 left++ ;
19                 right-- ;
20             }else{
21                 return false ;
22             }
23             
24         }
25         return true ;
26     }
27 }
原文地址:https://www.cnblogs.com/mengchunchen/p/7692548.html