Skip to content

Commit cf0b643

Browse files
committed
feat: Palindromic Substrings
1 parent 1af7efe commit cf0b643

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

palindromic-substrings/HodaeSsi.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# space complexity: O(n^2)
2+
# time complexity: O(n^2) (*exactly, n^2 / 2)
3+
class Solution:
4+
def countSubstrings(self, s: str) -> int:
5+
dp = [[False] * len(s) for _ in range(len(s))] # dp[i][j] = True if s[i:j+1] is a palindrome
6+
for i in range(len(s)):
7+
for j in range(i, -1, -1):
8+
if i == j:
9+
dp[j][i] = True
10+
continue
11+
if i - j == 1:
12+
dp[j][i] = s[i] == s[j]
13+
continue
14+
if s[i] == s[j]:
15+
if dp[j+1][i-1]:
16+
dp[j][i] = True
17+
18+
return sum([sum(row) for row in dp])
19+

0 commit comments

Comments
 (0)