Skip to content

Commit 5e1c7d7

Browse files
authored
Update Valid Palindrome II.java
1 parent 8ac764a commit 5e1c7d7

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

Easy/Valid Palindrome II.java

+13-19
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,21 @@
11
class Solution {
22
public boolean validPalindrome(String s) {
3-
int start = 0;
4-
int end = s.length() - 1;
5-
while (start < end && s.charAt(start) == s.charAt(end)) {
6-
start++;
7-
end--;
8-
}
9-
if (start >= end) {
10-
return true;
11-
}
12-
if (isPalindrome(s.substring(start + 1, end + 1)) || isPalindrome(s.substring(start, end))) {
3+
int[] firstPalindromeCheck = isPalindromHelper(s);
4+
if (firstPalindromeCheck[0] == -1) {
135
return true;
146
}
15-
return false;
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;
1610
}
17-
18-
private boolean isPalindrome(String s) {
19-
int start = 0;
20-
int end = s.length() - 1;
21-
while (start < end && s.charAt(start) == s.charAt(end)) {
22-
start++;
23-
end--;
11+
12+
private int[] isPalindromHelper(String s) {
13+
int startIdx = 0;
14+
int endIdx = s.length() - 1;
15+
while (startIdx < endIdx && s.charAt(startIdx) == s.charAt(endIdx)) {
16+
startIdx++;
17+
endIdx--;
2418
}
25-
return start >= end;
19+
return startIdx >= endIdx ? new int[]{-1} : new int[]{startIdx, endIdx};
2620
}
2721
}

0 commit comments

Comments
 (0)