dp
to store palindrome information such that dp[i][j]
is true if s[i...j]
is a palindrome.dp[i][i]
to true for all i
(single character is a palindrome).dp[i][i+1]
to true if s[i] == s[i+1]
for all i
(two same characters next to each other are a palindrome).dp
using dynamic programming. For each length l
from 3 to n
, check for all i
if s[i] == s[i+l-1]
and dp[i+1][i+l-2]
is true, then set dp[i][i+l-1]
to true.solve(i)
that returns the maximum number of palindromic substrings starting from index i
.solve(i)
, if i
is at the end of the string, return 0.memo[i]
is not -1, return memo[i]
(use memoization).result
to solve(i+1)
(skip the current index).j
from i+k
to n
, if dp[i][j-1]
is true, set result
to the maximum of result
and solve(j)+1
.result
in memo[i]
and return it.solve(0)
and return its result as the final answer.