File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(n)
3
+
4
+ class Solution {
5
+ public:
6
+ // Manacher's Algorithm
7
+ string longestPalindrome (string s) {
8
+ string T = preProcess (s);
9
+ int n = T.length ();
10
+ vector<int > P (n);
11
+ int C = 0 , R = 0 ;
12
+ for (int i = 1 ; i < n-1 ; i++) {
13
+ int i_mirror = 2 *C-i; // equals to i' = C - (i-C)
14
+
15
+ P[i] = (R > i) ? min (R-i, P[i_mirror]) : 0 ;
16
+
17
+ // Attempt to expand palindrome centered at i
18
+ while (T[i + 1 + P[i]] == T[i - 1 - P[i]])
19
+ P[i]++;
20
+
21
+ // If palindrome centered at i expand past R,
22
+ // adjust center based on expanded palindrome.
23
+ if (i + P[i] > R) {
24
+ C = i;
25
+ R = i + P[i];
26
+ }
27
+ }
28
+
29
+ // Find the maximum element in P.
30
+ int maxLen = 0 ;
31
+ int centerIndex = 0 ;
32
+ for (int i = 1 ; i < n-1 ; i++) {
33
+ if (P[i] > maxLen) {
34
+ maxLen = P[i];
35
+ centerIndex = i;
36
+ }
37
+ }
38
+
39
+ return s.substr ((centerIndex - 1 - maxLen)/2 , maxLen);
40
+ }
41
+ private:
42
+ string preProcess (string s) {
43
+ int n = s.length ();
44
+ if (n == 0 ) return " ^$" ;
45
+ string ret = " ^" ;
46
+ for (int i = 0 ; i < n; i++)
47
+ ret += " #" + s.substr (i, 1 );
48
+
49
+ ret += " #$" ;
50
+ return ret;
51
+ }
52
+ };
You can’t perform that action at this time.
0 commit comments