/290. Word Pattern

290. Word Pattern

Easy
Hash Table43.9% acceptance

Given a string pattern consisting of lowercase English letters and a string text consisting of lowercase English words separated by single spaces, determine if there exists a bijection between the characters in pattern and the words in text such that each character maps to exactly one unique word and each word maps to exactly one unique character. Return True if such a bijection exists, otherwise return False.

Example 1

Input: pattern=xyyx, text=red blue blue red

Output: True

Explanation: Each x maps to red, each y maps to blue. Bijective mapping exists.

Example 2

Input: pattern=xyyx, text=red blue blue green

Output: False

Explanation: Last word does not match the bijection.

Example 3

Input: pattern=xxxx, text=red blue blue red

Output: False

Explanation: Multiple words for same character, not bijective.

Constraints

  • 1 <= len(pattern) <= 300
  • pattern consists only of lowercase English letters
  • 1 <= len(text) <= 3000
  • text consists only of lowercase English letters and spaces
  • text does not contain leading or trailing spaces
  • All words in text are separated by a single space
Python (current runtime)

Case 1

Input: pattern='abc', text='one two three'

Expected: True

Case 2

Input: pattern='aba', text='one two one'

Expected: True

Case 3

Input: pattern='abc', text='one one one'

Expected: False

Case 4

Input: pattern='aabb', text='cat cat dog dog'

Expected: True

Case 5

Input: pattern='abca', text='dog cat fish dog'

Expected: True

Case 6

Input: pattern='abca', text='dog cat fish cat'

Expected: False