Longest Match Tokenizer
GooglePhone screenEasy
You are given a string text and a dictionary that maps words to integer ids.
Part 1: Longest match scan
Given a string text and a dictionary that maps words to integer ids, turn text into a list of tokens by scanning it from left to right.
At each position, find the longest dictionary word that starts there. If one matches, append its id as an integer and continue right after that word. If no word starts there, append the single character at that position as a string and move to the next character.
Matching is exact and case-sensitive. The scan never goes back: once a word is taken, the next position to look at is the one right after it. Return the tokens in order.
- Example 1
- text
"theater"- dictionary
{"a":3,"the":1,"theater":2}- Output
[2]
Why: Both
theandtheaterstart at position 0, andtheateris longer, so the result is its id alone. - Example 2
- text
"the theater is a"- dictionary
{"a":3,"the":1,"theater":2}- Output
[1," ",2," ","i","s"," ",3]
Why:
thegives 1, the space matches nothing and stays as" ",theatergives 2, then the space,iandsand another space stay as characters, andagives 3. - Example 3
- text
"abcx"- dictionary
{"c":3,"ab":1,"abcd":2}- Output
[1,3,"x"]
Why:
abcdwould be the longest word at position 0, but the text there isabcx, so the longest word that matches isab. Thencmatches, andxmatches nothing.
Constraints
0 <= len(text) <= 10^50 <= len(dictionary) <= 10^41 <= len(word) <= 20for every word indictionary0 <= dictionary[word] <= 10^9textand every word contain only lowercase letters and spaces