Skip to content

Commit 877b16b

Browse files
authored
Create 647.Palindromic-Substrings_v2.cpp
1 parent 70cd175 commit 877b16b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
int countSubstrings(string s)
4+
{
5+
string t = "#";
6+
for (auto ch: s)
7+
{
8+
t.push_back(ch);
9+
t.push_back('#');
10+
}
11+
12+
int n = t.size();
13+
vector<int>P(n);
14+
int maxCenter = -1;
15+
int maxRight = -1;
16+
for (int i=0; i<n; i++)
17+
{
18+
int r;
19+
if (i <= maxRight)
20+
{
21+
int j = maxCenter*2-i;
22+
r = min(P[j], maxRight-i);
23+
while (i-r>=0 && i+r<n && t[i-r]==t[i+r])
24+
r++;
25+
}
26+
else
27+
{
28+
r = 0;
29+
while (i-r>=0 && i+r<n && t[i-r]==t[i+r])
30+
r++;
31+
}
32+
P[i] = r-1;
33+
if (i+P[i]>maxRight)
34+
{
35+
maxRight = i+P[i];
36+
maxCenter = i;
37+
}
38+
}
39+
40+
int ret = 0;
41+
for (int i=0; i<n; i++)
42+
{
43+
ret += (P[i]+1)/2;
44+
}
45+
return ret;
46+
}
47+
};

0 commit comments

Comments
 (0)