码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 680: Valid Palindrome II

时间:2018-01-28 11:18:06      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:ati   lin   leetcode   may   post   xpl   private   most   star   

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.
 1 public class Solution {
 2     public bool ValidPalindrome(string s) {
 3         return s == null || s.Length < 2 || IsValid(s, 0, s.Length - 1, false);
 4     }
 5     
 6     private bool IsValid(string s, int start, int end, bool hasDeleted)
 7     {
 8         if (start >= end) return true;
 9         
10         int i = start, j = end;
11         
12         while (i < j)
13         {
14             if (s[i] != s[j])
15             {
16                 if (hasDeleted) return false;
17                 
18                 // we can try delete s[i] or s[j]
19                 if (IsValid(s, i + 1, j, true) || IsValid(s, i, j - 1, true))
20                 {
21                     return true;
22                 }
23                 
24                 return false;
25             }
26             
27             i++;
28             j--;
29         }
30         
31         return true;
32     }
33 }

 

Leetcode 680: Valid Palindrome II

标签:ati   lin   leetcode   may   post   xpl   private   most   star   

原文地址:https://www.cnblogs.com/liangmou/p/8370074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!