Google questions

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.

  1. Example 1
    text
    "theater"
    dictionary
    {"a":3,"the":1,"theater":2}
    Output
    [2]

    Why: Both the and theater start at position 0, and theater is longer, so the result is its id alone.

  2. Example 2
    text
    "the theater is a"
    dictionary
    {"a":3,"the":1,"theater":2}
    Output
    [1," ",2," ","i","s"," ",3]

    Why: the gives 1, the space matches nothing and stays as " ", theater gives 2, then the space, i and s and another space stay as characters, and a gives 3.

  3. Example 3
    text
    "abcx"
    dictionary
    {"c":3,"ab":1,"abcd":2}
    Output
    [1,3,"x"]

    Why: abcd would be the longest word at position 0, but the text there is abcx, so the longest word that matches is ab. Then c matches, and x matches nothing.

Constraints

  • 0 <= len(text) <= 10^5
  • 0 <= len(dictionary) <= 10^4
  • 1 <= len(word) <= 20 for every word in dictionary
  • 0 <= dictionary[word] <= 10^9
  • text and every word contain only lowercase letters and spaces
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question