2707. Extra Characters in a String
Problem
Split s into non-overlapping substrings that are words of dictionary; characters not covered by any word are "extra". Return the minimum possible number of extra characters.
Example: s = "leetscode", dictionary = ["leet","code","leetcode"] → 1 (the s)
Constraints: length ≤ 50; up to 50 words.
Word Break, minimized: dp[i] = fewest extra characters in s[i:]. Either skip s[i] (cost 1 + dp[i+1]) or, for every dictionary word starting at i, jump past it for free. A trie over the dictionary avoids rebuilding substrings.
Complexity: O(n² · L) with substring hashing (n, L ≤ 50).
class Solution:
def minExtraChar(self, s: str, dictionary: List[str]) -> int:
words, n = set(dictionary), len(s)
dp = [0] * (n + 1)
for i in range(n - 1, -1, -1):
dp[i] = 1 + dp[i + 1]
for j in range(i + 1, n + 1):
if s[i:j] in words:
dp[i] = min(dp[i], dp[j])
return dp[0]
assert Solution().minExtraChar("leetscode", ["leet", "code", "leetcode"]) == 1
assert Solution().minExtraChar("sayhelloworld", ["hello", "world"]) == 3
assert Solution().minExtraChar("abc", ["d"]) == 3
assert Solution().minExtraChar("abc", ["abc", "a"]) == 0
class Solution {
public int minExtraChar(String s, String[] dictionary) {
Set<String> words = new HashSet<>(Arrays.asList(dictionary));
int n = s.length();
int[] dp = new int[n + 1];
for (int i = n - 1; i >= 0; i--) {
dp[i] = 1 + dp[i + 1];
for (int j = i + 1; j <= n; j++) if (words.contains(s.substring(i, j))) dp[i] = Math.min(dp[i], dp[j]);
}
return dp[0];
}
}
func minExtraChar(s string, dictionary []string) int {
words, n := map[string]bool{}, len(s)
for _, w := range dictionary {
words[w] = true
}
dp := make([]int, n+1) // dp[i] = fewest extra characters in s[i:]
for i := n - 1; i >= 0; i-- {
dp[i] = 1 + dp[i+1] // s[i] is extra
for j := i + 1; j <= n; j++ {
if words[s[i:j]] {
dp[i] = min(dp[i], dp[j])
}
}
}
return dp[0]
}