Skip to content

Commit eda20ca

Browse files
committed
solved palindromic-substrings
1 parent 8b22e3f commit eda20ca

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

palindromic-substrings/sun912.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
TC: O(n^2)
3+
4+
TC in first try was O(n^3).
5+
It is the improved codes from neetcodes
6+
key point is that each character in loop is considered to middle one.
7+
Ant then, check left end and right end.
8+
9+
"""
10+
class Solution:
11+
def countSubstrings(self, s: str) -> int:
12+
result = 0
13+
for i in range(len(s)):
14+
result += self.countPalindrom(s, i, i)
15+
result += self.countPalindrom(s, i, i+1)
16+
return result
17+
18+
19+
def countPalindrom(self, s, left_end, right_end):
20+
result = 0
21+
while left_end >= 0 and right_end < len(s) and s[left_end] == s[right_end]:
22+
result += 1
23+
left_end -= 1
24+
right_end += 1
25+
26+
return result

0 commit comments

Comments
 (0)