Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 02e3174

Browse files
aQuaaQua
aQua
authored and
aQua
committed
290 accepted.
1 parent 90b7111 commit 02e3174

File tree

3 files changed

+98
-0
lines changed

3 files changed

+98
-0
lines changed
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# [290. Word Pattern](https://leetcode.com/problems/word-pattern/)
2+
3+
## 题目
4+
5+
Given a pattern and a string str, find if str follows the same pattern.
6+
7+
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
8+
9+
Examples:
10+
11+
```text
12+
pattern = "abba", str = "dog cat cat dog" should return true.
13+
pattern = "abba", str = "dog cat cat fish" should return false.
14+
pattern = "aaaa", str = "dog cat cat dog" should return false.
15+
pattern = "abba", str = "dog dog dog dog" should return false.
16+
```
17+
18+
Notes:
19+
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
20+
21+
Credits:Special thanks to @minglotus6 for adding this problem and creating all test cases.
22+
23+
## 解题思路
24+
25+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package Problem0290
2+
3+
import (
4+
"strings"
5+
)
6+
7+
func wordPattern(pattern string, str string) bool {
8+
ps := strings.Split(pattern, "")
9+
ss := strings.Split(str, " ")
10+
if len(ps) != len(ss) {
11+
return false
12+
}
13+
return match(ps, ss) && match(ss, ps)
14+
}
15+
16+
func match(s1, s2 []string) bool {
17+
size := len(s1)
18+
m := make(map[string]string, size)
19+
var i int
20+
var w string
21+
var ok bool
22+
for i = 0; i < size; i++ {
23+
if w, ok = m[s1[i]]; ok {
24+
if w != s2[i] {
25+
return false
26+
}
27+
} else {
28+
m[s1[i]] = s2[i]
29+
}
30+
}
31+
return true
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package Problem0290
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
// tcs is testcase slice
11+
var tcs = []struct {
12+
pattern string
13+
str string
14+
ans bool
15+
}{
16+
17+
{"abba", "dog cat cat dog", true},
18+
{"abba", "dog cat cat fish", false},
19+
{"aaaa", "dog cat cat dog", false},
20+
{"abba", "dog dog dog dog", false},
21+
{"aaa", "aa aa aa aa", false},
22+
23+
// 可以有多个 testcase
24+
}
25+
26+
func Test_wordPattern(t *testing.T) {
27+
ast := assert.New(t)
28+
29+
for _, tc := range tcs {
30+
fmt.Printf("~~%v~~\n", tc)
31+
ast.Equal(tc.ans, wordPattern(tc.pattern, tc.str), "输入:%v", tc)
32+
}
33+
}
34+
35+
func Benchmark_wordPattern(b *testing.B) {
36+
for i := 0; i < b.N; i++ {
37+
for _, tc := range tcs {
38+
wordPattern(tc.pattern, tc.str)
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)