diff --git a/problems/letter-combinations-of-a-phone-number/letter_combinations_of_a_phone_number.go b/problems/letter-combinations-of-a-phone-number/letter_combinations_of_a_phone_number.go index d03c853d3..fa59a8637 100644 --- a/problems/letter-combinations-of-a-phone-number/letter_combinations_of_a_phone_number.go +++ b/problems/letter-combinations-of-a-phone-number/letter_combinations_of_a_phone_number.go @@ -1 +1,33 @@ package letter_combinations_of_a_phone_number + +func letterCombinations(digits string) []string { + if digits == "" { + return nil + } + m := map[rune][]string{ + '2': {"a", "b", "c"}, + '3': {"d", "e", "f"}, + '4': {"g", "h", "i"}, + '5': {"j", "k", "l"}, + '6': {"m", "n", "o"}, + '7': {"p", "q", "r", "s"}, + '8': {"t", "u", "v"}, + '9': {"w", "x", "y", "z"}, + } + ans := make([]string, 1) + for _, k := range digits { + idx, t := 0, make([]string, len(ans)) + copy(t, ans) + for _, s := range t { + for _, c := range m[k] { + if idx < len(ans) { + ans[idx] = s + c + } else { + ans = append(ans, s+c) + } + idx++ + } + } + } + return ans +} diff --git a/problems/letter-combinations-of-a-phone-number/letter_combinations_of_a_phone_number_test.go b/problems/letter-combinations-of-a-phone-number/letter_combinations_of_a_phone_number_test.go index d03c853d3..346b1eaa3 100644 --- a/problems/letter-combinations-of-a-phone-number/letter_combinations_of_a_phone_number_test.go +++ b/problems/letter-combinations-of-a-phone-number/letter_combinations_of_a_phone_number_test.go @@ -1 +1,30 @@ package letter_combinations_of_a_phone_number + +import ( + "reflect" + "testing" +) + +type caseType struct { + input string + expected []string +} + +func TestLetterCombinations(t *testing.T) { + tests := [...]caseType{ + { + input: "", + expected: nil, + }, + { + input: "23", + expected: []string{"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"}, + }, + } + for _, tc := range tests { + output := letterCombinations(tc.input) + if !reflect.DeepEqual(output, tc.expected) { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}