Skip to content

Commit 8a945a7

Browse files
authored
Update Valid Palindrome II.java
1 parent 2c23741 commit 8a945a7

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

Easy/Valid Palindrome II.java

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,26 @@
11
class Solution {
22
public boolean validPalindrome(String s) {
3-
int[] firstPalindromeCheck = isPalindromHelper(s);
4-
if (firstPalindromeCheck[0] == -1) {
5-
return true;
6-
}
7-
int[] skipLeft = isPalindromHelper(s.substring(firstPalindromeCheck[0] + 1, firstPalindromeCheck[1] + 1));
8-
int[] skipRight = isPalindromHelper(s.substring(firstPalindromeCheck[0], check[1]));
9-
return skipLeft[0] == -1 || skipRight[0] == -1;
10-
}
11-
12-
private int[] isPalindromHelper(String s) {
133
int startIdx = 0;
144
int endIdx = s.length() - 1;
15-
while (startIdx < endIdx && s.charAt(startIdx) == s.charAt(endIdx)) {
5+
while (startIdx < endIdx) {
6+
if (s.charAt(startIdx) != s.charAt(endIdx)) {
7+
return isPalindromeWithDeletion(s, startIdx + 1, endIdx) ||
8+
isPalindromeWithDeletion(s, startIdx, endIdx - 1);
9+
}
10+
startIdx++;
11+
endIdx--;
12+
}
13+
return true;
14+
}
15+
16+
private boolean isPalindromeWithDeletion(String s, int startIdx, int endIdx) {
17+
while (startIdx < endIdx) {
18+
if (s.charAt(startIdx) != s.charAt(endIdx)) {
19+
return false;
20+
}
1621
startIdx++;
1722
endIdx--;
1823
}
19-
return startIdx >= endIdx ? new int[]{-1} : new int[]{startIdx, endIdx};
24+
return true;
2025
}
2126
}

0 commit comments

Comments
 (0)