Given a string s, return trueif it is possible to split the stringsinto three non-empty palindromic substrings. Otherwise, return false.
A string is said to be palindrome if it the same string when reversed.
Example 1:
Input: s = "abcbdd"
Output: true
Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.
Example 2:
Input: s = "bcbddxy"
Output: false
Explanation: s cannot be split into 3 palindromes.
Constraints:
3 <= s.length <= 2000
s consists only of lowercase English letters.
Solutions
Solution 1: Dynamic Programming
We define \(f[i][j]\) to indicate whether the substring of \(s\) from the \(i\)-th character to the \(j\)-th character is a palindrome, initially \(f[i][j] = \textit{true}\).
Then we can calculate \(f[i][j]\) using the following state transition equation:
Since \(f[i][j]\) depends on \(f[i + 1][j - 1]\), we need to enumerate \(i\) from large to small and \(j\) from small to large, so that when calculating \(f[i][j]\), \(f[i + 1][j - 1]\) has already been calculated.
Next, we enumerate the right endpoint \(i\) of the first substring and the right endpoint \(j\) of the second substring. The left endpoint of the third substring can be enumerated in the range \([j + 1, n - 1]\), where \(n\) is the length of the string \(s\). If the first substring \(s[0..i]\), the second substring \(s[i+1..j]\), and the third substring \(s[j+1..n-1]\) are all palindromes, then we have found a feasible partitioning scheme and return \(\textit{true}\).
After enumerating all partitioning schemes, if no valid partitioning scheme is found, return \(\textit{false}\).
Time complexity is \(O(n^2)\), and space complexity is \(O(n^2)\). Where \(n\) is the length of the string \(s\).