Skip to content

Commit d0ffa80

Browse files
authored
palindromic substrings solution
1 parent e1f412a commit d0ffa80

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
}

0 commit comments

Comments
 (0)