Skip to content

Commit 545d416

Browse files
Alagappan MaruthappanAlagappan Maruthappan
Alagappan Maruthappan
authored and
Alagappan Maruthappan
committed
count number of palindromic substring
1 parent f0f30b6 commit 545d416

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

count_palindrome_substring.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# https://leetcode.com/problems/palindromic-substrings/description/
2+
3+
4+
class Solution:
5+
def countSubstrings(self, s):
6+
"""
7+
:type s: str
8+
:rtype: int
9+
"""
10+
ans = 0
11+
N = len(s)
12+
DP = [[False] * N for i in range(N)]
13+
for i in range(N):
14+
DP[i][i] = True
15+
ans += 1
16+
for i in range(N-1):
17+
if s[i] == s[i+1]:
18+
DP[i][i+1] = True
19+
ans += 1
20+
for size in range(3, N + 1):
21+
for start in range(N-size+1):
22+
end = start + size - 1
23+
if s[start] == s[end] and DP[start+1][end-1]:
24+
DP[start][end] = True
25+
ans += 1
26+
return ans
27+
28+
29+
assert Solution().countSubstrings("aaa") == 6

0 commit comments

Comments
 (0)