Skip to content

Commit 21b0db5

Browse files
author
openset
committed
Add: Letter Combinations of a Phone Number
1 parent 0861184 commit 21b0db5

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1,33 @@
11
package letter_combinations_of_a_phone_number
2+
3+
func letterCombinations(digits string) []string {
4+
if digits == "" {
5+
return nil
6+
}
7+
m := map[rune][]string{
8+
'2': {"a", "b", "c"},
9+
'3': {"d", "e", "f"},
10+
'4': {"g", "h", "i"},
11+
'5': {"j", "k", "l"},
12+
'6': {"m", "n", "o"},
13+
'7': {"p", "q", "r", "s"},
14+
'8': {"t", "u", "v"},
15+
'9': {"w", "x", "y", "z"},
16+
}
17+
ans := make([]string, 1)
18+
for _, k := range digits {
19+
idx, t := 0, make([]string, len(ans))
20+
copy(t, ans)
21+
for _, s := range t {
22+
for _, c := range m[k] {
23+
if idx < len(ans) {
24+
ans[idx] = s + c
25+
} else {
26+
ans = append(ans, s+c)
27+
}
28+
idx++
29+
}
30+
}
31+
}
32+
return ans
33+
}
Original file line numberDiff line numberDiff line change
@@ -1 +1,30 @@
11
package letter_combinations_of_a_phone_number
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input string
10+
expected []string
11+
}
12+
13+
func TestLetterCombinations(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: "",
17+
expected: nil,
18+
},
19+
{
20+
input: "23",
21+
expected: []string{"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"},
22+
},
23+
}
24+
for _, tc := range tests {
25+
output := letterCombinations(tc.input)
26+
if !reflect.DeepEqual(output, tc.expected) {
27+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)