Skills101
← All coding problems

Follow the Word Pattern

easyStrings II+10 XPTime limit 2s

A sentence follows a letter pattern if there is a one-to-one match between pattern letters and words: the same letter always stands for the same word, and different letters always stand for different words. abba matches dog cat cat dog, but not dog cat cat fish and not dog dog dog dog.

Input:

  • line 1: the pattern (lowercase letters)
  • line 2: the words, separated by single spaces

Output: true if the sentence follows the pattern, otherwise false. A different number of letters and words means false.

Constraints: 1 ≤ pattern length ≤ 10⁴, 1 ≤ number of words ≤ 10⁴, each word is 1–10 lowercase letters.

Think about it: the same idea as isomorphic strings, with words instead of letters on one side: a map from letter to word and a map from word to letter, both must stay consistent.

Sample input 1

abba
dog cat cat dog

Sample output 1

true

Sample input 2

abba
dog dog dog dog

Sample output 2

false

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.