|
| 1 | +# [1745. Palindrome Partitioning IV](https://leetcode.com/problems/palindrome-partitioning-iv) |
| 2 | + |
| 3 | +## Description |
| 4 | + |
| 5 | +<div class="elfjS" data-track-load="description_content"><p>Given a string <code>s</code>, return <code>true</code> <em>if it is possible to split the string</em> <code>s</code> <em>into three <strong>non-empty</strong> palindromic substrings. Otherwise, return </em><code>false</code>.</p> |
| 6 | + |
| 7 | +<p>A string is said to be palindrome if it the same string when reversed.</p> |
| 8 | + |
| 9 | +<p> </p> |
| 10 | +<p><strong class="example">Example 1:</strong></p> |
| 11 | + |
| 12 | +<pre><strong>Input:</strong> s = "abcbdd" |
| 13 | +<strong>Output:</strong> true |
| 14 | +<strong>Explanation: </strong>"abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes. |
| 15 | +</pre> |
| 16 | + |
| 17 | +<p><strong class="example">Example 2:</strong></p> |
| 18 | + |
| 19 | +<pre><strong>Input:</strong> s = "bcbddxy" |
| 20 | +<strong>Output:</strong> false |
| 21 | +<strong>Explanation: </strong>s cannot be split into 3 palindromes. |
| 22 | +</pre> |
| 23 | + |
| 24 | +<p> </p> |
| 25 | +<p><strong>Constraints:</strong></p> |
| 26 | + |
| 27 | +<ul> |
| 28 | + <li><code>3 <= s.length <= 2000</code></li> |
| 29 | + <li><code>s</code> consists only of lowercase English letters.</li> |
| 30 | +</ul> |
| 31 | +</div> |
| 32 | + |
| 33 | +<p> </p> |
| 34 | + |
| 35 | +## Solutions |
| 36 | + |
| 37 | +**Solution: `Dynamic Programming`** |
| 38 | + |
| 39 | +- Time complexity: <em>O(n<sup>2</sup>)</em> |
| 40 | +- Space complexity: <em>O(n<sup>2</sup>)</em> |
| 41 | + |
| 42 | +<p> </p> |
| 43 | + |
| 44 | +### **JavaScript** |
| 45 | + |
| 46 | +```js |
| 47 | +/** |
| 48 | + * @param {string} s |
| 49 | + * @return {boolean} |
| 50 | + */ |
| 51 | +const checkPartitioning = function (s) { |
| 52 | + const n = s.length; |
| 53 | + const dp = Array.from({ length: n }, () => new Array(n).fill(null)); |
| 54 | + |
| 55 | + const isPalindrome = (a, b) => { |
| 56 | + if (a >= b) return true; |
| 57 | + if (dp[a][b] !== null) return dp[a][b]; |
| 58 | + const result = s[a] === s[b] && isPalindrome(a + 1, b - 1); |
| 59 | + |
| 60 | + dp[a][b] = result; |
| 61 | + |
| 62 | + return result; |
| 63 | + }; |
| 64 | + |
| 65 | + for (let a = 0; a < n - 2; a++) { |
| 66 | + const segment1 = isPalindrome(0, a); |
| 67 | + |
| 68 | + if (!segment1) continue; |
| 69 | + |
| 70 | + for (let b = a + 1; b < n - 1; b++) { |
| 71 | + const segment2 = isPalindrome(a + 1, b); |
| 72 | + |
| 73 | + if (!segment2) continue; |
| 74 | + const segment3 = isPalindrome(b + 1, n - 1); |
| 75 | + |
| 76 | + if (segment3) return true; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return false; |
| 81 | +}; |
| 82 | +``` |
0 commit comments