2707. Extra Characters in a String #601
-
Topics: You are given a 0-indexed string Return the minimum number of extra characters left over if you break up Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can define a Approach:
Let's implement this solution in PHP: 2707. Extra Characters in a String <?php
/**
* @param String $s
* @param String[] $dictionary
* @return Integer
*/
function minExtraChar($s, $dictionary) {
$n = strlen($s);
// Initialize the dp array with large values (representing infinity)
$dp = array_fill(0, $n + 1, $n);
$dp[0] = 0; // Base case: no extra characters for an empty string
// Convert dictionary array to a hash set for faster lookups
$dict = array_flip($dictionary);
// Iterate over the string
for ($i = 1; $i <= $n; $i++) {
// Assume the current character is extra
$dp[$i] = $dp[$i - 1] + 1;
// Check all possible substrings ending at index i-1
for ($j = 0; $j < $i; $j++) {
$substring = substr($s, $j, $i - $j);
if (isset($dict[$substring])) {
$dp[$i] = min($dp[$i], $dp[$j]);
}
}
}
// The answer is the minimum extra characters at the end of the string
return $dp[$n];
}
// Test cases
echo minExtraChar("leetscode", ["leet","code","leetcode"]); // Output: 1
echo "\n";
echo minExtraChar("sayhelloworld", ["hello","world"]); // Output: 3
?> Explanation:
Test Results:For the input For the input |
Beta Was this translation helpful? Give feedback.
We can define a
dp
array wheredp[i]
represents the minimum number of extra characters in the substrings[0:i]
after optimal segmentation.Approach:
Dynamic Programming Definition:
dp[i]
be the minimum number of extra characters in the substrings[0:i]
.dp[i]
, we can:s[i-1]
as an extra character and move to the next index.i
exists in the dictionary, and if it does, then use it to reduce extra characters.Transition:
i
, we either:dp[i-1]
if we treats[i]
as an extra character.s[j:i]
(forj < i
) and ifs[j:i]
is in the dictionary, …