|
3 | 3 | * SC: O(n)
|
4 | 4 | * */
|
5 | 5 | function countSubstrings(s: string): number {
|
6 |
| - const str = "#" + s.split("").join("#") + "#"; |
7 |
| - const len = str.length; |
8 |
| - const pal = new Array(len).fill(0); |
9 |
| - let center = 0, |
10 |
| - radius = 0, |
11 |
| - total = 0; |
| 6 | + const transformedString = "#" + s.split("").join("#") + "#"; |
| 7 | + const transformedStringLength = transformedString.length; |
| 8 | + const palindromeLengths = new Array(transformedStringLength).fill(0); |
| 9 | + let currentCenter = 0, |
| 10 | + rightBoundary = 0, |
| 11 | + totalPalindromeCount = 0; |
12 | 12 |
|
13 |
| - for (let i = 0; i < len; i++) { |
| 13 | + for (let i = 0; i < transformedStringLength; i++) { |
14 | 14 | // If i is within the rightmost center, copy the palindromes value from the mirror
|
15 |
| - if (i < radius) { |
16 |
| - pal[i] = Math.min(radius - i, pal[center * 2 - i]); |
| 15 | + if (i < rightBoundary) { |
| 16 | + palindromeLengths[i] = Math.min( |
| 17 | + rightBoundary - i, |
| 18 | + palindromeLengths[currentCenter * 2 - i], |
| 19 | + ); |
17 | 20 | }
|
18 | 21 |
|
19 | 22 | // Expand around i until it's not a palindrome and not over left or right
|
20 | 23 | while (
|
21 |
| - i + pal[i] + 1 < len && |
22 |
| - i - pal[i] - 1 >= 0 && |
23 |
| - str[i + pal[i] + 1] === str[i - pal[i] - 1] |
| 24 | + i + palindromeLengths[i] + 1 < transformedStringLength && |
| 25 | + i - palindromeLengths[i] - 1 >= 0 && |
| 26 | + transformedString[i + palindromeLengths[i] + 1] === |
| 27 | + transformedString[i - palindromeLengths[i] - 1] |
24 | 28 | ) {
|
25 |
| - pal[i]++; |
| 29 | + palindromeLengths[i]++; |
26 | 30 | }
|
27 | 31 |
|
28 | 32 | // If palindromes value is the new rightmost center, update center and right
|
29 |
| - if (i + pal[i] > radius) { |
30 |
| - center = i; |
31 |
| - radius = i + pal[i]; |
| 33 | + if (i + palindromeLengths[i] > radius) { |
| 34 | + currentCenter = i; |
| 35 | + rightBoundary = i + palindromeLengths[i]; |
32 | 36 | }
|
33 | 37 |
|
34 | 38 | // Add the number of palindromes with center i to the result
|
35 |
| - total += Math.floor((pal[i] + 1) / 2); |
| 39 | + total += Math.floor((palindromeLengths[i] + 1) / 2); |
36 | 40 | }
|
37 | 41 |
|
38 | 42 | return total;
|
|
0 commit comments