-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0647-PalindromicSubstrings.cs
50 lines (42 loc) · 1.36 KB
/
0647-PalindromicSubstrings.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//-----------------------------------------------------------------------------
// Runtime: 68ms
// Memory Usage: 22.1 MB
// Link: https://leetcode.com/submissions/detail/371206163/
//-----------------------------------------------------------------------------
using System;
using System.Linq;
namespace LeetCode
{
public class _0647_PalindromicSubstrings
{
public int CountSubstrings(string s)
{
if (string.IsNullOrEmpty(s)) return 0;
if (s.Length == 1) return 1;
int n2 = s.Length * 2 + 1;
var s2 = new char[n2];
for (int i = 0; i < s.Length; i++)
{
s2[i * 2] = '#';
s2[i * 2 + 1] = s[i];
}
s2[n2 - 1] = '#';
var p = new int[n2];
var range_max = 0;
var center = 0;
for (int i = 1; i < n2 - 1; i++)
{
if (range_max > i)
p[i] = Math.Min(p[center * 2 - i], range_max - i);
while (i - 1 - p[i] >= 0 && i + 1 + p[i] < n2 && s2[i - 1 - p[i]] == s2[i + 1 + p[i]])
p[i]++;
if (i + p[i] > range_max)
{
range_max = i + p[i];
center = i;
}
}
return (p.Sum() + s.Length) / 2;
}
}
}