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: TrueExample 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.
验证回文字符串II。题意跟版本一很接近,版本一问的只是input是不是回文,版本二问的是如果允许最多删除一个字符,问剩下的内容还是不是回文。这里可删可不删。思路还是双指针往中间逼近,同时需要写一个helper函数帮助判断回文情况。while循环的一开始,如果两边的char相同,就往中间逼近;如果不同,则判断这两种情况里面是否有任意一个能return true,因为只要有一个return true就说明删除一个字符,剩下的部分是有效的。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public boolean validPalindrome(String s) { 3 int left = 0; 4 int right = s.length() - 1; 5 while (left < right && s.charAt(left) == s.charAt(right)) { 6 left++; 7 right--; 8 } 9 if (helper(s, left + 1, right)) { 10 return true; 11 } 12 if (helper(s, left, right - 1)) { 13 return true; 14 } 15 return false; 16 } 17 18 private boolean helper(String s, int left, int right) { 19 while (left < right) { 20 if (s.charAt(left) != s.charAt(right)) { 21 return false; 22 } 23 left++; 24 right--; 25 } 26 return true; 27 } 28 }
JavaScript实现
1 /** 2 * @param {string} s 3 * @return {boolean} 4 */ 5 var validPalindrome = function (s) { 6 let left = 0; 7 let right = s.length - 1; 8 while (left < right && s[left] === s[right]) { 9 left++; 10 right--; 11 } 12 if (checkPalindrome(s, left + 1, right)) { 13 return true; 14 } 15 if (checkPalindrome(s, left, right - 1)) { 16 return true; 17 } 18 return false; 19 }; 20 21 var checkPalindrome = function (s, left, right) { 22 while (left < right) { 23 if (s[left] !== s[right]) { 24 return false; 25 } 26 left++; 27 right--; 28 } 29 return true; 30 };
相关题目