Skip to content

Commit 9d96048

Browse files
committed
0290. 单词规律
1 parent a74554e commit 9d96048

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package leetcode_0290_word_pattern
2+
3+
import "strings"
4+
5+
// 0290. 单词规律
6+
// https://leetcode.cn/problems/word-pattern/
7+
8+
// wordPattern 哈希表
9+
// 时间复杂度: O(n)
10+
// 空间复杂度: O(n)
11+
// 注意: 双向匹配
12+
// 例1:
13+
// 输入: pattern="abba", s="dog dog dog dog"
14+
// 输出: false
15+
func wordPattern(pattern string, s string) bool {
16+
ss := strings.Split(s, " ")
17+
pLen, sLen := len(pattern), len(ss)
18+
if pLen != sLen {
19+
return false
20+
}
21+
22+
m := make(map[byte]string)
23+
set := make(map[string]bool)
24+
for i := range pattern {
25+
if v, ok := m[pattern[i]]; !ok {
26+
if !set[ss[i]] {
27+
m[pattern[i]] = ss[i]
28+
set[ss[i]] = true
29+
} else {
30+
return false
31+
}
32+
} else {
33+
if v != ss[i] {
34+
return false
35+
}
36+
}
37+
}
38+
39+
return true
40+
}

0 commit comments

Comments
 (0)