File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
String/647.Palindromic-Substrings Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments