diff --git a/problems/verifying-an-alien-dictionary/verifying_an_alien_dictionary.go b/problems/verifying-an-alien-dictionary/verifying_an_alien_dictionary.go index 79c4170b3..c46d08829 100644 --- a/problems/verifying-an-alien-dictionary/verifying_an_alien_dictionary.go +++ b/problems/verifying-an-alien-dictionary/verifying_an_alien_dictionary.go @@ -1 +1,21 @@ package verifying_an_alien_dictionary + +func isAlienSorted(words []string, order string) bool { + m := make(map[byte]int) + for i := len(order) - 1; i >= 0; i-- { + m[order[i]] = i + } + if len(words) > 1 { + for pre, word := range words[1:] { + l, wl := len(words[pre]), len(word) + for i := 0; i < l; i++ { + if wl <= i || m[words[pre][i]] > m[word[i]] { + return false + } else if m[words[pre][i]] < m[word[i]] { + break + } + } + } + } + return true +} diff --git a/problems/verifying-an-alien-dictionary/verifying_an_alien_dictionary_test.go b/problems/verifying-an-alien-dictionary/verifying_an_alien_dictionary_test.go index 79c4170b3..463ed0b7e 100644 --- a/problems/verifying-an-alien-dictionary/verifying_an_alien_dictionary_test.go +++ b/problems/verifying-an-alien-dictionary/verifying_an_alien_dictionary_test.go @@ -1 +1,35 @@ package verifying_an_alien_dictionary + +import "testing" + +type caseType struct { + words []string + order string + expected bool +} + +func TestIsAlienSorted(t *testing.T) { + tests := [...]caseType{ + { + words: []string{"hello", "leetcode"}, + order: "hlabcdefgijkmnopqrstuvwxyz", + expected: true, + }, + { + words: []string{"word", "world", "row"}, + order: "worldabcefghijkmnpqstuvxyz", + expected: false, + }, + { + words: []string{"apple", "app"}, + order: "abcdefghijklmnopqrstuvwxyz", + expected: false, + }, + } + for _, tc := range tests { + output := isAlienSorted(tc.words, tc.order) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.words, output, tc.expected) + } + } +}