Letters to words
Check that a sentence follows a pattern like "abba". About 9 minutes.
Letters stand for words
The pattern "abba" and the sentence "dog cat cat dog" match: a stands for dog, b for cat. It's the renaming from the last step, except each letter now stands for a whole word.
Split the sentence into words, then pair each pattern letter with the word in the same position. Keep two maps again, letter to word and word to letter, so no letter has two words and no word has two letters.
4 letters and 4 words: the counts match, so it's worth checking.
Check the counts first
If the number of words doesn't equal the number of letters, some letter has no word, or some word has no letter. There's no need to look further: the answer is no.
"dog dog dog dog" doesn't follow "abba": a and b would both stand for dog.
words = s.split()
if len(words) != len(pattern):
return False
to_word, to_letter = {}, {}
for ch, w in zip(pattern, words):
if to_word.get(ch, w) != w:
return False
if to_letter.get(w, ch) != ch:
return False
to_word[ch], to_letter[w] = w, ch
return TrueDoes "dog dog dog dog" follow the pattern "abba"?
- ANo
- BYes
- CNo, the lengths differ
Show the answer
No. a and b would both stand for dog.
Follows the pattern?
You get a pattern of lowercase letters and a sentence of words separated by single spaces. Return true if there is a one-to-one match between letters and words so that the sentence follows the pattern.
pattern = "abba", s = "dog cat cat dog" → true
0 ≤ pattern length ≤ 300 · 0 ≤ s length ≤ 3,000 · single spaces, none at the ends