Algorithm/src/main/java/All/ValidPalindrome.java
2025-09-27 12:25:49 +08:00

41 lines
1.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package All;
/**
* 题目: 680. 验证回文串 II
* 描述:给你一个字符串 s最多 可以从中删除一个字符。
* 请你判断 s 是否能成为回文字符串:如果能,返回 true ;否则,返回 false 。
示例 1
输入s = "aba"
输出true
* 链接https://leetcode.cn/problems/valid-palindrome-ii/
*/
public class ValidPalindrome {
public boolean validPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
if (s.charAt(l) == s.charAt(r)) {
l++; r--;
} else {
// 尝试跳过左边或右边的字符
return isPalindrome(s, l + 1, r) || isPalindrome(s, l, r - 1);
}
}
return true;
}
private boolean isPalindrome(String s, int l, int r) {
while (l < r) {
if (s.charAt(l++) != s.charAt(r--)) return false;
}
return true;
}
public static void main(String[] args) {
ValidPalindrome solution = new ValidPalindrome();
String s="bddb";
solution.validPalindrome(s);
}
}