|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +/** |
| 4 | + * An O(N) Solution (Manacher’s Algorithm): |
| 5 | + * S = “abaaba”, T = “#a#b#a#a#b#a#”. |
| 6 | + */ |
| 7 | +public class LongestPalindrome { |
| 8 | + public static void main(String[] args) { |
| 9 | + String s = "cabaaba"; |
| 10 | + System.out.println(s); |
| 11 | + |
| 12 | + String longestPalindrome = longestPalindrome(s); |
| 13 | + System.out.println(longestPalindrome); |
| 14 | + } |
| 15 | + |
| 16 | + public static String preProcess(String s) { |
| 17 | + String T = ""; |
| 18 | + for (int i = 0; i < s.length(); ++i) |
| 19 | + T += "#" + s.substring(i, i + 1); |
| 20 | + |
| 21 | + T += "#"; |
| 22 | + return T; |
| 23 | + } |
| 24 | + |
| 25 | + public static String longestPalindrome(String s) { |
| 26 | + String T = preProcess(s); |
| 27 | + int N = T.length(); |
| 28 | + int[] p = new int[N]; // record the range |
| 29 | + int center = 1; // the center |
| 30 | + int R = 0; // the range, not including itself |
| 31 | + |
| 32 | + for (int i = 1; i < N; ++i) { |
| 33 | + int i_mirror = center - (i - center); |
| 34 | + p[i] = (R > i) ? Math.min(R - i, p[i_mirror]) : 0; |
| 35 | + |
| 36 | + while (i - 1 - p[i] >= 0 && i + 1 + p[i] < N) { |
| 37 | + if (T.charAt(i + 1 + p[i]) == T.charAt(i - 1 - p[i])) |
| 38 | + p[i]++; |
| 39 | + else |
| 40 | + break; |
| 41 | + } |
| 42 | + |
| 43 | + if (i + p[i] > R) { |
| 44 | + R = i + p[i]; |
| 45 | + center = i; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + int maxLength = 0; |
| 50 | + int centerIndex = 0; |
| 51 | + for (int i = 1; i < N - 1; ++i) { |
| 52 | + if (p[i] > maxLength) { |
| 53 | + maxLength = p[i]; |
| 54 | + centerIndex = i; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + int start = (centerIndex-maxLength) / 2; |
| 59 | + return s.substring(start, start+maxLength); |
| 60 | + |
| 61 | + } |
| 62 | +} |
| 63 | + |
0 commit comments