Extra Characters in a String

You are given a string `s` and a dictionary of distinct words `dictionary`. Break `s` into one or more non-overlapping substrings so that each substring is a word in `dictionary`. Some characters of `s` may not belong to any chosen substring; they are extra. Return the minimum number of extra characters when you break `s` up optimally.

30:00

Extra Characters in a String
medium
Free written solution
Topics
Companies

You are given a string s and a dictionary of distinct words dictionary. Break s into one or more non-overlapping substrings so that each substring is a word in dictionary. Some characters of s may not belong to any chosen substring; they are extra. Return the minimum number of extra characters when you break s up optimally.

Example 1:
Input: {"s":"leetscode","dictionary":["leet","code","leetcode"]}
Output: 1
Constraints:
  • 1≤s.length≤501 \leq s.\text{length} \leq 50

  • 1≤dictionary.length≤501 \leq dictionary.\text{length} \leq 50

  • 1≤dictionary[i].length≤501 \leq dictionary[i].\text{length} \leq 50

  • s and dictionary[i] consist of lowercase English letters

  • dictionary contains distinct words

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"leetscode","dictionary":["leet","code","leetcode"]}
start
0
1
2
3
4
5
6
7
8
·
l
e
e
t
s
c
o
d
e
0
·
·
·
·
·
·
·
·
·

bottom row: dp[k] = fewest extra letters among the first k letters (the start column is dp[0])

dp[i] is the fewest extra characters in the first i letters. dp[0] = 0: the empty prefix wastes nothing. The dictionary has 3 word(s).

■ extra letter■ word being tried■ dictionary word
Variables
No variables to display
DepthFunction Call
Stack empty
0/13