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 return true.pattern =
"abba"
, str ="dog cat cat fish"
should return false.pattern =
"aaaa"
, str ="dog cat cat dog"
should return false.pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Notes:
You may assumepattern
contains only lowercase letters, andstr
contains lowercase letters separated by a single space.
这里就用一个hashmap把字母与单词的对应关系存起来。边loop边检查已经对应好的关系是否被破坏。例如已经被map好的字母对应不同的单词;又或者字母还没出现但对应的单词已经出现。T:O(m), S:O(m) m是pattern的长度。
Last updated