Manacher 算法 容易理解,实现起来也没什么大坑,复杂度还是 O(n)的, 花半个小时实现下很有意思
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
| class Solution { public String longestPalindrome(String s) { StringBuilder sb = new StringBuilder(2 + 2 * s.length()); sb.append("^"); for (int i = 0; i < s.length(); i++) { sb.append("#").append(s.charAt(i)); } sb.append("#$"); String s2 = sb.toString(); int maxStart = 1, max = 0, rC = 1, rR = 1; int[] p = new int[s2.length()]; for (int i = 1; i < s2.length() - 1; i++ ) { p[i] = i < rR ? Math.min(p[2 * rC - i], rR - i) : 0; while (s2.charAt(i+p[i]+1) == s2.charAt(i - p[i] - 1)) { p[i] = p[i]+1; } if (i + p[i] > rR) { rC = i; rR = i + p[i]; } if (p[i] > max) { maxStart = i - p[i]; max = p[i]; } }
return s2.substring(maxStart,maxStart + 2*max+1).replace("#", ""); } }
|