Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6aecce8

Browse files
ADD Palindromic-Substrings problem #60
1 parent 59a4c92 commit 6aecce8

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

‎Medium/palindromic-substrings.cs

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
using System;
2+
using System.Text;
3+
4+
public class Solution
5+
{
6+
#region Brute Force
7+
private static bool _IsPalindrome(string s)
8+
{
9+
if (string.IsNullOrWhiteSpace(s))
10+
{
11+
return false;
12+
}
13+
14+
if (s.Length == 1)
15+
{
16+
return true;
17+
}
18+
19+
for (int i = 0; i <= s.Length / 2; i++)
20+
{
21+
if (s[i] != s[s.Length - i - 1])
22+
{
23+
return false;
24+
}
25+
}
26+
27+
return true;
28+
}
29+
public static int CountSubstrings(string s)
30+
{
31+
if (string.IsNullOrWhiteSpace(s))
32+
{
33+
return 0;
34+
}
35+
36+
int count = s.Length;
37+
StringBuilder sb = new StringBuilder();
38+
39+
for (int i = 0; i < s.Length; i++)
40+
{
41+
sb.Clear();
42+
sb.Append(s[i]);
43+
44+
for (int j = i + 1; j < s.Length; j++)
45+
{
46+
sb.Append(s[j]);
47+
if (_IsPalindrome(sb.ToString()))
48+
{
49+
count++;
50+
}
51+
}
52+
}
53+
54+
return count;
55+
}
56+
#endregion
57+
58+
#region Two-Pointers
59+
private static int _CountPalindrome(string s, int left, int right)
60+
{
61+
int count = 0;
62+
while (left >= 0 && right < s.Length && s[left] == s[right])
63+
{
64+
count++;
65+
66+
left--;
67+
right++;
68+
}
69+
70+
return count;
71+
}
72+
public static int CountSubstrings2(string s)
73+
{
74+
if (string.IsNullOrWhiteSpace(s))
75+
{
76+
return 0;
77+
}
78+
79+
int count = 0;
80+
81+
for (int i = 0; i < s.Length; i++)
82+
{
83+
// Odd Length Palindrome
84+
count += _CountPalindrome(s, i, i);
85+
86+
// Even Length Palindrome
87+
count += _CountPalindrome(s, i, i + 1);
88+
}
89+
90+
return count;
91+
}
92+
#endregion
93+
94+
public static void Main(string[] args)
95+
{
96+
Console.WriteLine(CountSubstrings("abaaba"));
97+
Console.WriteLine(CountSubstrings2("abaaba"));
98+
99+
Console.ReadKey();
100+
}
101+
}
102+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /