-
Notifications
You must be signed in to change notification settings - Fork 0
/
Palindrome Substrings.py
65 lines (51 loc) · 1.81 KB
/
Palindrome Substrings.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def CountPS(str, n):
# creat empty 2-D matrix that counts
# all palindrome substring. dp[i][j]
# stores counts of palindromic
# substrings in st[i..j]
dp = [[0 for x in range(n)]
for y in range(n)]
# P[i][j] = true if substring str[i..j]
# is palindrome, else false
P = [[False for x in range(n)]
for y in range(n)]
# palindrome of single length
for i in range(n):
P[i][i] = True
# palindrome of length 2
for i in range(n - 1):
if (str[i] == str[i + 1]):
P[i][i + 1] = True
dp[i][i + 1] = 1
# Palindromes of length more than 2. This
# loop is similar to Matrix Chain Multiplication.
# We start with a gap of length 2 and fill DP
# table in a way that the gap between starting and
# ending indexes increase one by one by
# outer loop.
for gap in range(2, n):
# Pick a starting point for the current gap
for i in range(n - gap):
# Set ending point
j = gap + i
# If current string is palindrome
if (str[i] == str[j] and P[i + 1][j - 1]):
P[i][j] = True
# Add current palindrome substring ( + 1)
# and rest palindrome substring (dp[i][j-1] +
# dp[i+1][j]) remove common palindrome
# substrings (- dp[i+1][j-1])
if (P[i][j] == True):
dp[i][j] = (dp[i][j - 1] +
dp[i + 1][j] + 1 - dp[i + 1][j - 1])
else:
dp[i][j] = (dp[i][j - 1] +
dp[i + 1][j] - dp[i + 1][j - 1])
# return total palindromic substrings
return dp[0][n - 1]
# Driver Code
if __name__ == "__main__":
str = "racecar"
n = len(str)
print(CountPS(str, n))
# This code is contributed by ita_c