Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

def count_decomps(s):

n = len(s)

# DP table
NPS = [[{'num': 0, 'ispal': False} for _ in range(n)] for _ in range(n)]

# Base cases
for i in range(n):
NPS[i][i]['num'] = 1
NPS[i][i]['ispal'] = True

for l in range(2, n + 1):


for i in range(n - l + 1):
j=i+l-1

if s[i] == s[j]:
if l == 2 or NPS[i + 1][j - 1]['ispal']:
NPS[i][j]['num'] = NPS[i + 1][j - 1]['num'] + 1
NPS[i][j]['ispal'] = True

if not NPS[i][j]['ispal']:
NPS[i][j]['num'] = NPS[i][j - 1]['num'] + NPS[i + 1][j]['num'] - NPS[i + 1][j - 1]['num']

return NPS[0][n - 1]['num']

s = 'madam'
numberDec = count_decomps(s)
print(numberDec)

You might also like