Skip to content

Commit 937f9a9

Browse files
author
openset
committed
Add: Word Pattern
1 parent c270302 commit 937f9a9

File tree

2 files changed

+78
-2
lines changed

2 files changed

+78
-2
lines changed

problems/word-pattern/word_pattern.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,23 @@
1-
package word_pattern
1+
package problem_290
2+
3+
import "strings"
4+
5+
func wordPattern(pattern string, str string) bool {
6+
ss, l := strings.Split(str, " "), len(pattern)
7+
m, e := make(map[byte]string), make(map[string]bool)
8+
if len(ss) != l {
9+
return false
10+
}
11+
for i := 0; i < l; i++ {
12+
if s, ok := m[pattern[i]]; ok {
13+
if ss[i] != s {
14+
return false
15+
}
16+
} else if e[ss[i]] {
17+
return false
18+
} else {
19+
m[pattern[i]], e[ss[i]] = ss[i], true
20+
}
21+
}
22+
return true
23+
}
Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,55 @@
1-
package word_pattern
1+
package problem_290
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
pattern string
7+
str string
8+
expected bool
9+
}
10+
11+
func TestWordPattern(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
pattern: "abba",
15+
str: "dog cat cat dog",
16+
expected: true,
17+
},
18+
{
19+
pattern: "abba",
20+
str: "dog cat cat fish",
21+
expected: false,
22+
},
23+
{
24+
pattern: "aaaa",
25+
str: "dog cat cat dog",
26+
expected: false,
27+
},
28+
{
29+
pattern: "abba",
30+
str: "dog dog dog dog",
31+
expected: false,
32+
},
33+
{
34+
pattern: "abba",
35+
str: "dog cat cat dog fish",
36+
expected: false,
37+
},
38+
{
39+
pattern: "abba",
40+
str: "b a a b",
41+
expected: true,
42+
},
43+
{
44+
pattern: "abba",
45+
str: "b c c b",
46+
expected: true,
47+
},
48+
}
49+
for _, tc := range tests {
50+
output := wordPattern(tc.pattern, tc.str)
51+
if output != tc.expected {
52+
t.Fatalf("input: %v, output: %v, expected: %v", tc.pattern, output, tc.expected)
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)