306. Word Pattern

Easy
Bidirectional Mapping
Hashing

Problem

Given a pattern and a space-separated string s, determine whether s follows the same pattern. Each pattern character must map to exactly one word and each word must map to exactly one pattern character.

Examples

Example 1

Input: "abba", "dog cat cat dog"
Output: true

Example 2

Input: "abba", "dog cat cat fish"
Output: false

Example 3

Input: "aaaa", "dog cat cat dog"
Output: false
Constraints

1 <= pattern.length <= 300

s contains lowercase English words separated by single spaces.

Hints

?? Split s into words first.

?? The number of words must equal pattern.length.

?? Use a bijection between pattern characters and words.

Expected Complexity
Time: O(n)
Space: O(n)
Follow-up

Can you implement the bijection using last-seen positions?

Practice Notes

Attempts: 0

Time spent: 0min

Hints used: 0

00:00
Loading...
Case 1
Case 2
Case 3
Input
"abba", "dog cat cat dog"
Expected
true