File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ func countSubstrings (s string ) int {
2
+ runes := []rune {} // S(n) = O(n)
3
+ for _ , c := range s {
4
+ runes = append (runes , c )
5
+ runes = append (runes , '\000' )
6
+ }
7
+ ans := 0
8
+ dp := make ([]int , len (runes ) - 1 )
9
+ lastR := - 1
10
+ lastMid := - 1
11
+ i := 0
12
+ for i != len (dp ) { // Manacher T(n) = O(n)
13
+ diff := lastR - i
14
+ deviation := 0
15
+ if diff > 0 {
16
+ deviation = min (diff , dp [lastMid - (i - lastMid )])
17
+ }
18
+ l := i - deviation
19
+ r := i + deviation
20
+ for l != 0 && r + 1 != len (dp ) && runes [l - 1 ] == runes [r + 1 ] {
21
+ deviation ++
22
+ l --
23
+ r ++
24
+ }
25
+ dp [i ] = deviation
26
+ if r > lastR {
27
+ lastR = r
28
+ lastMid = i
29
+ }
30
+ if runes [i ] == '\000' {
31
+ ans += (deviation + 1 ) >> 1
32
+ } else {
33
+ ans += 1 + (deviation >> 1 )
34
+ }
35
+ i ++
36
+ }
37
+ return ans
38
+ }
You can’t perform that action at this time.
0 commit comments