diff --git a/problems/word-pattern/word_pattern.go b/problems/word-pattern/word_pattern.go index d7a3dd385..141aaef12 100644 --- a/problems/word-pattern/word_pattern.go +++ b/problems/word-pattern/word_pattern.go @@ -1 +1,23 @@ -package word_pattern +package problem_290 + +import "strings" + +func wordPattern(pattern string, str string) bool { + ss, l := strings.Split(str, " "), len(pattern) + m, e := make(map[byte]string), make(map[string]bool) + if len(ss) != l { + return false + } + for i := 0; i < l; i++ { + if s, ok := m[pattern[i]]; ok { + if ss[i] != s { + return false + } + } else if e[ss[i]] { + return false + } else { + m[pattern[i]], e[ss[i]] = ss[i], true + } + } + return true +} diff --git a/problems/word-pattern/word_pattern_test.go b/problems/word-pattern/word_pattern_test.go index d7a3dd385..935ba4f36 100644 --- a/problems/word-pattern/word_pattern_test.go +++ b/problems/word-pattern/word_pattern_test.go @@ -1 +1,55 @@ -package word_pattern +package problem_290 + +import "testing" + +type caseType struct { + pattern string + str string + expected bool +} + +func TestWordPattern(t *testing.T) { + tests := [...]caseType{ + { + pattern: "abba", + str: "dog cat cat dog", + expected: true, + }, + { + pattern: "abba", + str: "dog cat cat fish", + expected: false, + }, + { + pattern: "aaaa", + str: "dog cat cat dog", + expected: false, + }, + { + pattern: "abba", + str: "dog dog dog dog", + expected: false, + }, + { + pattern: "abba", + str: "dog cat cat dog fish", + expected: false, + }, + { + pattern: "abba", + str: "b a a b", + expected: true, + }, + { + pattern: "abba", + str: "b c c b", + expected: true, + }, + } + for _, tc := range tests { + output := wordPattern(tc.pattern, tc.str) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.pattern, output, tc.expected) + } + } +}