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 upsoptimally.
Input: s ="leetscode", dictionary =["leet","code","leetcode"]Output: 1Explanation: 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 return1.
Example 2:
1
2
3
Input: s ="sayhelloworld", dictionary =["hello","world"]Output: 3Explanation: 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 return3.
The dp(i) function returns the minimum number of extra characters from position i to the end of the string s.
Base Case: When i equals the length of s, we have processed the entire string, so we return 0.
Recursive Step:
Assume the character at position i is extra and call dp(i + 1) + 1.
Check all possible substrings starting from i to find if any substring is in the dictionary. If a substring s[i:j] is found in the dictionary, recursively call dp(j).
Memoization:
Memoize the results of the recursive calls to avoid redundant calculations and speed up the process.
defminExtraChars(s, dictionary):
dict_set = set(dictionary)
n = len(s)
memo = {}
defdp(i):
if i == n:
return0if i in memo:
return memo[i]
# Assume s[i] is an extra character min_extra = dp(i +1) +1# Try to find any substring starting at i that is in dictionaryfor j in range(i +1, n +1):
if s[i:j] in dict_set:
min_extra = min(min_extra, dp(j))
memo[i] = min_extra
return min_extra
return dp(0)
defminExtraChars(s, dictionary):
dict_set = set(dictionary)
n = len(s)
memo = {}
defdp(i):
if i == n:
return0if i in memo:
return memo[i]
# Assume s[i] is an extra character min_extra = dp(i +1) +1# Try to find any substring starting at i that is in dictionaryfor j in range(i +1, n +1):
if s[i:j] in dict_set:
min_extra = min(min_extra, dp(j))
memo[i] = min_extra
return min_extra
return dp(0)