forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestPlaindrome.java
56 lines (56 loc) · 1.64 KB
/
LongestPlaindrome.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
// Thanks to heartfire.cc
public class Solution {
public String longestPalindrome(String s) {
// Start typing your Java solution below
// DO NOT write main() function
//the following is an O(n2) solution, which is not optimal
int[] max = new int[s.length()];
//special case s.length() == 0
if (s.length() == 0) {
return new String();
}
//init to 0s
for (int i = 0; i < s.length(); i++) {
max[i] = 0;
}
//try for each possible center.
for (int c = 0; c < s.length(); c++) {
//the center is at c
int l = c, r = c;
while (l >= 0 && r < s.length()) {
if (s.charAt(l) == s.charAt(r)) {
max[c] = r - l + 1;
}
else {
break;
}
l--;
r++;
}
//the center is between c and c+1
l = c;
r = c+1;
while (l >= 0 && r < s.length()) {
if (s.charAt(l) == s.charAt(r)) {
if (max[c] < r - l + 1) {
max[c] = r - l + 1;
}
}
else {
break;
}
l--;
r++;
}
}
//find the max
int m = 0, index = 0;
for (int i = 0 ; i < s.length(); i++) {
if (m < max[i]) {
m = max[i];
index = i;
}
}
return s.substring(index-(max[index] - 1)/2, index + max[index]/2 + 1);
}
}