Implement a simplified greedy longest-match tokenizer, the kind of scan used in many NLP pipelines. You are given a string text and a list of strings vocab holding the tokenizer's vocabulary. Scan text from left to right and, at each position, consume the longest token from vocab that matches the upcoming characters.
If no token in vocab matches at the current position, emit the special token "<UNK>" for that single character and advance by one position. Consecutive unknown characters each produce their own "<UNK>" token (one per character).
Return the resulting list of tokens in the order they were produced.
Function Signature
def tokenize(text: str, vocab: list[str]) -> list[str]:
Rules
-
A vocabulary token
t
matches at position
i
when
text[i:i + len(t)] == t
.
-
When a token matches, emit it and advance past all of its characters. The choice at each position is final: the scan never goes back to try a shorter token, even if a shorter one would let more of the string match later.
-
"<UNK>"
is a literal output string. It is never in
vocab
, since vocabulary tokens use lowercase letters only.
Constraints
-
1 <= len(text) <= 10^4
-
1 <= len(vocab) <= 1000
-
Each token in
vocab
consists of lowercase English letters only.
-
1 <= len(token) <= 20
for each token in
vocab
.
-
text
consists of lowercase English letters only.
-
All tokens in
vocab
are unique.
Examples
Input: text = "lowerthelower", vocab = ["low", "lower", "the", "er", "lo"]
Output: ["lower", "the", "lower"]
At index 0 the longest match is "lower" (length 5), ahead of "low" and "lo". Then "the" matches at index 5 and "lower" matches again at index 8, which reaches the end of the string.
Input: text = "abcxyz", vocab = ["ab", "abc", "yz"]
Output: ["abc", "<UNK>", "yz"]
At index 0, "abc" (length 3) is the longest match. At index 3 no token starts with x, so it becomes "<UNK>". At index 4, "yz" matches.
Input: text = "abcd", vocab = ["ab", "abc", "cd"]
Output: ["abc", "<UNK>"]
The scan takes "abc" at index 0, the longest match there, even though "ab" followed by "cd" would cover the whole string. No token matches "d" at index 3, so it becomes "<UNK>".