generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem53.cs
More file actions
41 lines (35 loc) · 1 KB
/
Problem53.cs
File metadata and controls
41 lines (35 loc) · 1 KB
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
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/palindromic-substrings/">Palindromic Substrings</see>.
/// </summary>
public static class Problem53
{
/// <summary>
/// Given a string s, return the number of palindromic substrings in it.
/// Time complexity: O(n^2).
/// Space complexity: O(n).
/// </summary>
/// <param name="s">String to traverse.</param>
/// <returns>Number of palindromic substrings.</returns>
public static int CountSubstrings(string s)
{
if (string.IsNullOrEmpty(s))
{
return 0;
}
var count = 1;
for (var i = 1; i < s.Length; i++)
{
count += Traverse(s, i, i) + Traverse(s, i - 1, i);
}
return count;
}
private static int Traverse(string s, int left, int right)
{
if (left >= 0 && right < s.Length && s[left] == s[right])
{
return 1 + Traverse(s, left - 1, right + 1);
}
return 0;
}
}