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:
- 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 }