问题描述
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
测试样例
1 2
| Input: s = "aba" Output: true
|
1 2 3
| Input: s = "abca" Output: true Explanation: You could delete the character 'c'.
|
1 2
| Input: s = "abc" Output: false
|
说明
1 2
| 1 <= s.length <= 10^5 s consists of lowercase English letters.
|
解题
思路
采用双指针来求解。两个指针分别从两端向中间遍历,遇到不相同的字符时,分别剔除左侧和右侧的一个元素,判断其余子串是否回文。
补充:
- 双指针
substring()
函数是左闭右开区间
- 时间复杂度
O(n)
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { private boolean flag_delete = false; public boolean validPalindrome(String s) { int left = 0, right = s.length() - 1; while(left < right) { if(s.charAt(left) != s.charAt(right)) { if(flag_delete == true) { return false; } flag_delete = true; return validPalindrome(s.substring(left + 1, right + 1)) || validPalindrome(s.substring(left, right)); } ++left; --right; } return true; } }
|