Leetcode 680: Valid Palindrome II

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 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‘.

 

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的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-680-Valid Palindrome II]

Leetcode 680: Valid Palindrome II

leetcode-680-Valid Palindrome II

Python 解LeetCode:680. Valid Palindrome II

LeetCode 680. 验证回文字符串 Ⅱ [Valid Palindrome II (Easy)]

LeetCode 680. 验证回文字符串 Ⅱ [Valid Palindrome II (Easy)]