I was trying to solve a question via dynamic programming. I have a string and I need to find all the possible palindromic substrings. Say, I have a string of length n
. I have created a matrix n*n
for the lookup. A cell (i,j)
is either 1 or 0. If it is 1, it means that the substring[i..j] is a palindrome, otherwise 0. Initially the diagonals are 1 because every character itself is a palindrome.
I need to fill the matrix properly as stated above.
I figured out the following:
- If substring[i..j] is a plaindrome, then I can find if substring[i-1..j+1] is palindrome in
O(1)
time by checking if matrix[i][j]==1 and word[i-1] == word[j+1]..
How can I go about filling the matrix, for other general cases.
A small explanation with pseudocode/language specific implementation to fill out the matrix will be much appreciated
Edit: I need some explanation as to how and in which order the matrix gets filled (i.e diagonally, horizontally etc) . I want to solve the question by filling out this matrix only, and by no other method. My question is not a duplicate of this