Skip to content

Commit 6a8ad7f

Browse files
authored
Update 1960.Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings.cpp
1 parent fa50158 commit 6a8ad7f

File tree

1 file changed

+21
-30
lines changed

1 file changed

+21
-30
lines changed

String/1960.Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings/1960.Maximum-Product-of-the-Length-of-Two-Palindromic-Substrings.cpp

Lines changed: 21 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,44 +2,35 @@ class Solution {
22
public:
33
long long maxProduct(string s)
44
{
5-
// Insert '#'
6-
string t = "$#";
7-
for (int i = 0; i < s.size(); ++i) {
8-
t += s[i];
9-
t += "#";
10-
}
11-
12-
// Process t
13-
vector<int> p(t.size(), 0);
14-
int mx = 0, id = 0, resLen = 0, resCenter = 0;
15-
for (int i = 1; i < t.size(); ++i)
5+
int n = s.size();
6+
int maxRight = -1;
7+
int maxCenter = -1;
8+
vector<int>P(n);
9+
for (int i=0; i<n; i++)
1610
{
17-
p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;
18-
while (t[i + p[i]] == t[i - p[i]]) ++p[i];
19-
if (mx < i + p[i]) {
20-
mx = i + p[i];
21-
id = i;
22-
}
23-
if (resLen < p[i]) {
24-
resLen = p[i];
25-
resCenter = i;
11+
int r;
12+
int j = maxCenter*2-i;
13+
if (i<=maxRight)
14+
r = min(P[j], maxRight-i);
15+
else
16+
r = 0;
17+
while (i-r>=0 && i+r<n && s[i-r]==s[i+r])
18+
r++;
19+
P[i] = r-1;
20+
if (i+P[i] > maxRight)
21+
{
22+
maxRight = i+P[i];
23+
maxCenter = i;
2624
}
2725
}
28-
29-
vector<int>len;
30-
for (int i=2; i<p.size(); i+=2)
31-
{
32-
len.push_back(p[i]/2);
33-
}
34-
35-
int n = s.size();
26+
3627

3728
vector<int>left(n, 0);
3829
left[0] = 1;
3930
int j = 0;
4031
for (int i=1; i<n; i++)
4132
{
42-
while (j<n && j+len[j]-1 < i)
33+
while (j<n && j+P[j] < i)
4334
j++;
4435
left[i] = max(left[i-1], (i-j)*2+1);
4536
}
@@ -49,7 +40,7 @@ class Solution {
4940
j = n-1;
5041
for (int i=n-2; i>=0; i--)
5142
{
52-
while (j>=0 && j-len[j]+1 > i)
43+
while (j>=0 && j-P[j] > i)
5344
j--;
5445
right[i] = max(right[i+1], (j-i)*2+1);
5546
}

0 commit comments

Comments
 (0)