-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidPalindromeII.java
More file actions
37 lines (31 loc) · 1 KB
/
Copy pathValidPalindromeII.java
File metadata and controls
37 lines (31 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package LeetcodePractice;
public class ValidPalindromeII {
public static void main(String[] args) {
System.out.println(validPalindrome("aba"));
System.out.println(validPalindrome("abca"));
System.out.println(validPalindrome("abc"));
System.out.println(validPalindrome("deeee"));
}
public static boolean validPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) == s.charAt(right)) {
left++;
right--;
} else {
return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
}
}
return true;
}
private static boolean isPalindrome(String s, int left, int right) {
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}