1593. Split a String Into the Max Number of Unique Substrings #731
-
Topics: Given a string You can split string A substring is a contiguous sequence of characters within a string. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a backtracking approach. This involves recursively trying to create substrings from the current position in the string and keeping track of the unique substrings we've used so far. Here's a step-by-step solution:
Let's implement this solution in PHP: 1593. Split a String Into the Max Number of Unique Substrings <?php
class Solution {
/**
* @param String $s
* @return Integer
*/
function maxUniqueSplit($s) {
// Call the backtracking function with an empty set and start index 0
return $this->backtrack($s, [], 0);
}
/**
* @param $s
* @param $used
* @param $start
* @return int|mixed
*/
private function backtrack($s, $used, $start) {
// If we've reached the end of the string, return the size of the used set
if ($start === strlen($s)) {
return count($used);
}
$maxCount = 0;
// Try to create substrings from start index to the end of the string
for ($end = $start + 1; $end <= strlen($s); $end++) {
// Get the current substring
$substring = substr($s, $start, $end - $start);
// Check if the substring is unique (not in the used set)
if (!in_array($substring, $used)) {
// Add the substring to the used set
$used[] = $substring;
// Recur for the next part of the string
$maxCount = max($maxCount, $this->backtrack($s, $used, $end));
// Backtrack: remove the last added substring
array_pop($used);
}
}
return $maxCount;
}
}
// Example usage
$solution = new Solution();
echo $solution->maxUniqueSplit("ababccc"); // Output: 5
echo "\n";
echo $solution->maxUniqueSplit("aba"); // Output: 2
echo "\n";
echo $solution->maxUniqueSplit("aa"); // Output: 1
?> Explanation:
Complexity
|
Beta Was this translation helpful? Give feedback.
We can use a backtracking approach. This involves recursively trying to create substrings from the current position in the string and keeping track of the unique substrings we've used so far.
Here's a step-by-step solution: