-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidPalindromeII.java
More file actions
49 lines (45 loc) · 1.28 KB
/
ValidPalindromeII.java
File metadata and controls
49 lines (45 loc) · 1.28 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
38
39
40
41
42
43
44
45
46
47
48
49
package string;
/**
* Created by Yang on 2017/9/19.
************************************************************************************************
* Given a non-empty string s, you may delete at most one character. Judge whether you can make
* it a palindrome.
*
* Example 1:
* Input: "aba"
* Output: true
*
* Example 2:
* Input: "abca"
* Output: true
* Explanation:
* You could delete the character 'c'.
*
* Note:
* The string will only contain lowercase characters a-z. The maximum length of the string
* is 50000.
************************************************************************************************
*/
public class ValidPalindromeII {
public boolean validPalindrome(String s) {
if (s == null || s.length() < 3) {
return true;
}
int lo = 0;
int hi = s.length() - 1;
while (lo < hi) {
if (s.charAt(lo++) != s.charAt(hi--)) {
return isPalindrome(s, lo, hi-1) || isPalindrome(s, lo+1, hi);
}
}
return true;
}
private boolean isPalindrome(String s, int lo, int hi) {
while (lo < hi) {
if (s.charAt(lo++) != s.charAt(hi--)) {
return false;
}
}
return true;
}
}