290 Word Pattern
Given apattern
and a stringstr
, find ifstr
follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter inpattern
and a non-empty word instr
.
Examples:
pattern =
"abba"
, str ="dog cat cat dog"
should returntrue
.pattern =
"abba"
, str ="dog cat cat fish"
should returnfalse
.pattern =
"aaaa"
, str ="dog cat cat dog"
should returnfalse
.pattern =
"abba"
, str ="dog dog dog dog"
should returnfalse
.
Notes:
You may assumepattern
contains only lowercase letters, andstr
contains lowercase letters separated by a single space.
The Idea: Use a bidirectional map to check for a one to one mapping between each character in the pattern and each word in the sentence.
Complexity: O(n) time and O(2n) space:
Last updated