Skip to content

Commit a74554e

Browse files
committed
0291. 单词规律 II
1 parent a7f86d1 commit a74554e

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package leetcode_0291_word_pattern_ii
2+
3+
// 0291. 单词规律 II
4+
// https://leetcode.cn/problems/word-pattern-ii/
5+
6+
// wordPatternMatch dfs+map
7+
// 时间复杂度: O(mn)
8+
// 空间复杂度: O(n)
9+
// 注意:双射映射 说明需要两个map
10+
// 推荐题解: https://leetcode.cn/problems/word-pattern-ii/solution/hui-su-hashmapbao-cun-pi-pei-hashsetbao-645u7/
11+
func wordPatternMatch(pattern string, s string) bool {
12+
var (
13+
pLen = len(pattern)
14+
sLen = len(s)
15+
m = make(map[byte]string)
16+
set = make(map[string]bool)
17+
dfs func(idx1, idx2 int) bool
18+
)
19+
dfs = func(idx1, idx2 int) bool {
20+
if idx1 == pLen {
21+
// 匹配完成
22+
if idx2 == sLen {
23+
return true
24+
} else {
25+
// s中有部分未被匹配到
26+
return false
27+
}
28+
}
29+
30+
// 之前添加过
31+
if v, ok := m[pattern[idx1]]; ok {
32+
if idx2+len(v) <= sLen && s[idx2:idx2+len(v)] == v {
33+
return dfs(idx1+1, idx2+len(v))
34+
} else {
35+
return false
36+
}
37+
}
38+
// 之前未添加过
39+
for i := idx2 + 1; i <= sLen; i++ {
40+
str := s[idx2:i]
41+
if !set[str] {
42+
set[str] = true
43+
m[pattern[idx1]] = str
44+
if dfs(idx1+1, i) {
45+
return true
46+
}
47+
delete(m, pattern[idx1])
48+
delete(set, str)
49+
}
50+
}
51+
return false
52+
}
53+
return dfs(0, 0)
54+
}

0 commit comments

Comments
 (0)