Extra Characters in a String Problem
Description
LeetCode Problem 2707.
You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary. There may be some extra characters in s which are not present in any of the substrings.
Return the minimum number of extra characters left over if you break up s optimally.
Example 1:
Input: s = "leetscode", dictionary = ["leet","code","leetcode"]
Output: 1
Explanation: We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1.
Example 2:
Input: s = "sayhelloworld", dictionary = ["hello","world"]
Output: 3
Explanation: We can break s in two substrings: "hello" from index 3 to 7 and "world" from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3.
Constraints:
1 <= s.length <= 501 <= dictionary.length <= 501 <= dictionary[i].length <= 50dictionary[i]andsconsists of only lowercase English lettersdictionarycontains distinct words
Solution
Approach: Dynamic Programming with a Set
Put the dictionary in a set. Let f[i] be the fewest extra characters in the first i characters of s, with f[0] = 0.
For i >= 1, either the last character is extra, giving f[i - 1] + 1, or some substring s[j..i) is a dictionary word, giving f[j]. Take the best of these. The answer is f[n].
Complexity: O(n3 + L) time (n start positions, n end positions, and the substring hash) and O(n + L) space, where L is the total length of the dictionary words.
class Solution:
def minExtraChar(self, s: str, dictionary: List[str]) -> int:
ss = set(dictionary)
n = len(s)
f = [0] * (n + 1)
for i in range(1, n + 1):
f[i] = f[i - 1] + 1
for j in range(i):
if s[j:i] in ss and f[j] < f[i]:
f[i] = f[j]
return f[n]