Longest Dictionary Tokenization
Problem statement
You are given a text string, a dictionary of token-to-id mappings, and one integer priority for each dictionary entry. Starting at the beginning of text, repeatedly choose among all dictionary tokens that match the current position.
Choose the matching entry with the highest priority. If several entries have the same priority, choose the longest token. If priority and token length both tie, choose the earliest dictionary entry. Emit the chosen entry's id and advance by its token length. If no dictionary token matches, emit the current character itself and advance by one character.
Return the sequence of emitted ids and literal characters. When all priorities are equal, this is the original longest-match tokenizer.
Function
encodeWithDictionary(text: String, dictionary: String[][], priorities: int[]) → String[]Examples
Example 1
text = "applepie"dictionary = [["app","B"],["apple","A"],["pie","P"]]priorities = [0,0,0]return = ["A","P"]All priorities tie, so apple is preferred over app by token length.
Example 2
text = "xabcd"dictionary = [["ab","1"],["abc","2"],["bc","3"]]priorities = [0,0,0]return = ["x","2","d"]The first character has no match. At index 1, abc wins the equal-priority tie because it is longer than ab.
Example 3
text = "abcdx"dictionary = [["abcd","4"],["abc","3"],["ab","2"]]priorities = [1,5,10]return = ["2","c","d","x"]ab has the highest priority, so it overrides the longer matching tokens. The remaining characters have no matches and are emitted literally.
Constraints
1 <= text.length <= 100000;textand every token contain lowercase English letters.1 <= dictionary.length == priorities.length <= 10000.- Each dictionary entry is
[token, id]; tokens are nonempty and ids are nonempty printable ASCII strings of length at most100. - The total length of all dictionary tokens is at most
100000. -1000000000 <= priorities[i] <= 1000000000.- The total length of all returned strings is at most
1000000.