64. Pattern to Words

A pattern made of lowercase letters and a sentence made of lowercase words separated by single spaces are given. The sentence follows the pattern if you can pair each pattern letter with one word so that reading the pattern letter by letter gives exactly the words of the sentence in order. The pairing must be one-to-one: the same letter always stands for the same word, and different letters stand for different words.

Return true if the sentence follows the pattern and false otherwise. If the number of letters differs from the number of words, the answer is false.

Example 1

Input:
pattern = "xyyx", sentence = "cat dog dog cat"
Output:
true
Explanation:

x stands for cat and y stands for dog, which reproduces the sentence exactly.

Example 2

Input:
pattern = "xy", sentence = "tea tea"
Output:
false
Explanation:

x and y would both have to stand for tea, but different letters need different words.

Constraints

1 ≤ pattern.length ≤ 300

1 ≤ sentence.length ≤ 3000

pattern contains lowercase letters; sentence contains lowercase letters and single spaces, with no leading or trailing space

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…