给定题干:
给定一个非空字符串
s
,请判断如果 最多 从字符串中删除一个字符能否得到一个回文字符串。题目来源:
力扣(LeetCode)
1.示例
如下:
示例 1:
输入: s = "aba"
输出: true
示例 2:
输入: s = "abca"
输出: true
解释: 可以删除 "c" 字符 或者 "b" 字符
示例 3:
输入: s = "abc"
输出: false
2.解答与注记
代码如下(Java):
class Solution {
public boolean validPalindrome(String s) {
int sL = s.length();
// 建立双指针分别指向字符串的首尾两端。
int low = 0, high = sL - 1;
while(low < high) {
char l = s.charAt(low), h = s.charAt(high);
// 比较俩个指针所指向的值是否相等
if(l == h) {
// 相等则移动俩个指针
low++;
high--;
}else {
// 不等时则以俩个指针中的一个为界,判断剩余部分是否为回文。
return isPalindrome(s,low + 1,high) || isPalindrome(s,low,high - 1);
}
}
return true;
}
public boolean isPalindrome(String s, int low, int high) {
while(low < high) {
char l = s.charAt(low), h = s.charAt(high);
if(l == h) {
low++;
high--;
}else {
// 在剩余部分的回文判断中再出现不等情况,则不能获得回文。
return false;
}
}
return true;
}
}
总结
以上就是今天要讲的内容,本文介绍了最多删除一个字符得到回文问题的解决方法,在此备忘以供参考。