131. Palindrome Partitioning #103
-
Topics: Given a string Example 1:
Example 2:
Constraints:
Footnotes |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a combination of backtracking and dynamic programming. The goal is to explore all possible partitions and check if each partition is a palindrome. Steps to Solve:
Let's implement this solution in PHP: 131. Palindrome Partitioning <?php
function partition($s) {
$result = [];
$current = [];
backtrack($s, 0, $current, $result);
return $result;
}
function backtrack($s, $start, &$current, &$result) {
if ($start >= strlen($s)) {
$result[] = $current;
return;
}
for ($end = $start; $end < strlen($s); $end++) {
if (isPalindrome(substr($s, $start, $end - $start + 1))) {
$current[] = substr($s, $start, $end - $start + 1);
backtrack($s, $end + 1, $current, $result);
array_pop($current);
}
}
}
function isPalindrome($s) {
$n = strlen($s);
for ($i = 0; $i < $n / 2; $i++) {
if ($s[$i] !== $s[$n - $i - 1]) {
return false;
}
}
return true;
}
// Example usage:
$s1 = "aab";
$s2 = "a";
print_r(partition($s1)); // Output: [["a","a","b"],["aa","b"]]
print_r(partition($s2)); // Output: [["a"]]
?> Explanation:
Time Complexity:
This solution works efficiently for the given constraint where the maximum length of the string is 16. |
Beta Was this translation helpful? Give feedback.
We can use a combination of backtracking and dynamic programming. The goal is to explore all possible partitions and check if each partition is a palindrome.
Steps to Solve:
Backtracking:
Palindrome Check:
Collect Results: