-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution647.cs
36 lines (32 loc) · 996 Bytes
/
Solution647.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
namespace LeetCode.Solutions;
public class Solution647
{
/// <summary>
/// 647. Palindromic Substrings - Medium
/// <a href="https://leetcode.com/problems/palindromic-substrings">See the problem</a>
/// </summary>
public int CountSubstrings(string s)
{
var n = s.Length;
var count = 0;
// Function to expand around the center and count palindromes
void ExpandAroundCenter(int left, int right)
{
while (left >= 0 && right < n && s[left] == s[right])
{
count++; // Found a palindrome
left--;
right++;
}
}
// Expand around every center
for (var i = 0; i < n; i++)
{
// Odd-length palindromes (single character center)
ExpandAroundCenter(i, i);
// Even-length palindromes (two character center)
ExpandAroundCenter(i, i + 1);
}
return count;
}
}