forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path005.Longest-Palindromic-Substring.cpp
50 lines (45 loc) · 1.17 KB
/
005.Longest-Palindromic-Substring.cpp
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
class Solution {
public:
string longestPalindrome(string s)
{
string t="#";
for (int i=0; i<s.size(); i++)
t+= s.substr(i,1)+"#";
int N = t.size();
vector<int>P(N,0);
int maxCenter = -1;
int maxRight = -1;
for (int i=0; i<N; i++)
{
int k;
if (i > maxRight)
{
k = 0;
while (i-k>=0 && i+k<N && t[i-k]==t[i+k]) k++;
}
else
{
k = min(P[maxCenter*2-i],maxRight-i);
while (i-k>=0 && i+k<N && t[i-k]==t[i+k]) k++;
}
P[i] = k-1;
if (i + P[i] > maxRight)
{
maxRight = i + P[i];
maxCenter = i;
}
}
// for (auto x:P) cout<<x<<" ";
int maxLen = -1;
int center;
for (int i=0; i<P.size(); i++)
{
if (P[i]>maxLen)
{
maxLen = P[i];
center = i;
}
}
return s.substr(center/2 - maxLen/2, maxLen);
}
};