|
| 1 | +# 2707. Extra Characters in a String |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Hash Table, String, Dynamic Programming, Trie. |
| 5 | +- Similar Questions: Word Break. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +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. |
| 10 | + |
| 11 | +Return **the **minimum** number of extra characters left over if you break up **`s`** optimally.** |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | +``` |
| 17 | +Input: s = "leetscode", dictionary = ["leet","code","leetcode"] |
| 18 | +Output: 1 |
| 19 | +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. |
| 20 | +
|
| 21 | +``` |
| 22 | + |
| 23 | +Example 2: |
| 24 | + |
| 25 | +``` |
| 26 | +Input: s = "sayhelloworld", dictionary = ["hello","world"] |
| 27 | +Output: 3 |
| 28 | +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. |
| 29 | +``` |
| 30 | + |
| 31 | + |
| 32 | +**Constraints:** |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | +- `1 <= s.length <= 50` |
| 37 | + |
| 38 | +- `1 <= dictionary.length <= 50` |
| 39 | + |
| 40 | +- `1 <= dictionary[i].length <= 50` |
| 41 | + |
| 42 | +- `dictionary[i]` and `s` consists of only lowercase English letters |
| 43 | + |
| 44 | +- `dictionary` contains distinct words |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | +## Solution |
| 49 | + |
| 50 | +```javascript |
| 51 | +/** |
| 52 | + * @param {string} s |
| 53 | + * @param {string[]} dictionary |
| 54 | + * @return {number} |
| 55 | + */ |
| 56 | +var minExtraChar = function(s, dictionary) { |
| 57 | + var map = dictionary.reduce((res, item) => { |
| 58 | + res[item] = 1; |
| 59 | + return res; |
| 60 | + }, {}); |
| 61 | + var dp = Array(s.length); |
| 62 | + for (var i = s.length - 1; i >= 0; i--) { |
| 63 | + dp[i] = (dp[i + 1] || 0) + 1; |
| 64 | + var str = ''; |
| 65 | + for (var j = i; j < s.length; j++) { |
| 66 | + str += s[j]; |
| 67 | + if (map[str]) { |
| 68 | + dp[i] = Math.min(dp[i], dp[j + 1] || 0); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + return dp[0]; |
| 73 | +}; |
| 74 | +``` |
| 75 | + |
| 76 | +**Explain:** |
| 77 | + |
| 78 | +Bottom-up dynamic programming. |
| 79 | + |
| 80 | +**Complexity:** |
| 81 | + |
| 82 | +* Time complexity : O(n ^ 2). |
| 83 | +* Space complexity : O(n). |
0 commit comments