-
Notifications
You must be signed in to change notification settings - Fork 2
/
LongestPalindrome.java
77 lines (62 loc) · 2.05 KB
/
LongestPalindrome.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package leetcode;
public class LongestPalindrome {
private String str = "";
// We will try to expand around the center.
// There are two kinds of centers: when the palindrome is odd and when it is even.
public String longestPalindrome(String s) {
str = s;
// To record the result.
String result = "";
int longest = 0;
// The length of the current palindrome.
int current = 0;
// The starting/ending point of the current palindrome.
int start;
int end;
int around;
int length;
// We start with those odd ones.
for (int i = 0; i < s.length(); i++) {
around = expandAroundOddCenter(i);
start = i - around;
end = i + around;
length = end - start + 1;
if (length > longest) {
result = str.substring(start, end + 1);
longest = length;
}
}
// We continue with those even ones.
for (int i = 1; i < s.length(); i++) {
around = expandAroundEvenCenter(i - 1, i);
start = i - 1 - around;
end = i + around;
length = end - start + 1;
if (length > longest) {
result = str.substring(start, end + 1);
longest = length;
}
}
return result;
}
private int expandAroundOddCenter(int center) {
int around = 0;
while (center - around >= 0 && center + around < str.length()) {
if (str.charAt(center - around) != str.charAt(center + around)) {
return around - 1;
}
around++;
}
return around - 1;
}
private int expandAroundEvenCenter(int left, int right) {
int around = 0;
while (left - around >= 0 && right + around < str.length()) {
if (str.charAt(left - around) != str.charAt(right + around)) {
return around - 1;
}
around++;
}
return around - 1;
}
}