Skip to content

Commit 8e8ee9b

Browse files
committed
add longestPalindrome.cpp
1 parent 5048d5b commit 8e8ee9b

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

C++/longestPalindrome.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
};

0 commit comments

Comments
 (0)