291 Word Pattern II
291. Word Pattern II
1. Question
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 substring instr
.
Examples:
pattern =
"abab"
, str ="redblueredblue"
should return true.pattern =
"aaaa"
, str ="asdasdasdasd"
should return true.pattern =
"aabb"
, str ="xyzabcxzyabc"
should return false.
Notes:
You may assume bothpattern
andstr
contains only lowercase letters.
2. Implementation
(1) Backtracking
3. Time & Space Complexity
Backtracking: 时间复杂度O(n * C(m, n)),n是str的长度, m为pattern的长度,这个问题相当于将str分成m份,而分的方法是C(n, m),每部分都要O(n)时间验证, 空间复杂度O(m + n + n) => O(m + n), 递归的所需空间最多为n, set的空间最多为n, map的空间最多为n
Last updated