Oh, no! You have accidentally removed all spaces, punctuation, and capitalization in a lengthy document. A sentence like "I reset the computer. It still didn't boot!" became "iresetthecomputeritstilldidntboot''. You'll deal with the punctuation and capitalization later; right now you need to re-insert the spaces. Most of the words are in a dictionary but a few are not. Given a dictionary (a list of strings) and the document (a string), design an algorithm to unconcatenate the document in a way that minimizes the number of unrecognized characters. Return the number of unrecognized characters.
Note: This problem is slightly different from the original one in the book.
Example:
Input:
dictionary = ["looked","just","like","her","brother"]
sentence = "jesslookedjustliketimherbrother"
Output: 7
Explanation: After unconcatenating, we got "jess looked just like tim her brother", which containing 7 unrecognized characters.
Note:
0 <= len(sentence) <= 1000
The total number of characters in dictionary is less than or equal to 150000.
There are only lowercase letters in dictionary and sentence.
Solutions
Solution 1
Thinking
Insert spaces so unrecognized characters are minimized. All segmentations are exponential; \(O(n^2)\) interval checks fit the limits.
\(dp[i]\) is the fewest unknowns in the first \(i\) characters. The last piece is either one unknown or a dictionary word \(sentence[j:i]\) transferring from \(dp[j]\).
A set makes membership \(O(1)\). \(dp[0]=0\) fills up to \(n\). No trie is needed while \(n\) stays moderate.