680.验证回文字符串 Ⅱ Java版本
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
题目描述:可以删除一个字符,判断是否能构成回文字符串。
思路:从左右两端开始验证是否是回文串,验证的过程中,若两个字符不等,再左右各加一或减一,验证一遍。
public boolean validPalindrome(String s
) {
for (int i
= 0, j
= s
.length() - 1; i
< j
; i
++, j
--) {
if (s
.charAt(i
) != s
.charAt(j
)) {
return isPalindrome(s
, i
, j
- 1) || isPalindrome(s
, i
+ 1, j
);
}
}
return true;
}
private boolean isPalindrome(String s
, int i
, int j
) {
while (i
< j
) {
if (s
.charAt(i
++) != s
.charAt(j
--)) {
return false;
}
}
return true;
}