parent
4b1fbe9bc9
commit
a92c066b09
@ -0,0 +1,37 @@
|
||||
package phoneletters
|
||||
|
||||
var digitToLetters = map[rune]string{
|
||||
'2': "abc",
|
||||
'3': "def",
|
||||
'4': "ghi",
|
||||
'5': "jkl",
|
||||
'6': "mno",
|
||||
'7': "pqrs",
|
||||
'8': "tuv",
|
||||
'9': "wxyz",
|
||||
}
|
||||
|
||||
func letterCombinations(digits string) []string {
|
||||
if digits == "" {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
combos := make([]string, 0, len(digits)*4)
|
||||
rest := letterCombinations(digits[1:])
|
||||
if len(rest) == 0 {
|
||||
rest = []string{""}
|
||||
}
|
||||
|
||||
letters := digitToLetters[rune(digits[0])]
|
||||
for _, letter := range letters {
|
||||
for _, r := range rest {
|
||||
combos = append(combos, string(letter)+r)
|
||||
}
|
||||
}
|
||||
|
||||
return combos
|
||||
}
|
||||
|
||||
func Combinations(digits string) []string {
|
||||
return letterCombinations(digits)
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package phoneletters_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.jxs.me/leetgo/phoneletters"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestEm(t *testing.T) {
|
||||
require.Equal(t, []string{}, phoneletters.Combinations(""))
|
||||
}
|
||||
|
||||
func TestSingle(t *testing.T) {
|
||||
require.Equal(t, []string{"a", "b", "c"}, phoneletters.Combinations("2"))
|
||||
}
|
||||
|
||||
func TestDoble(t *testing.T) {
|
||||
expected := []string{
|
||||
"ad", "ae", "af",
|
||||
"bd", "be", "bf",
|
||||
"cd", "ce", "cf",
|
||||
}
|
||||
|
||||
require.Equal(t, expected, phoneletters.Combinations("23"))
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
17. Letter Combinations of a Phone Number
|
||||
Medium
|
||||
|
||||
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
|
||||
|
||||
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: digits = "23"
|
||||
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: digits = ""
|
||||
Output: []
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: digits = "2"
|
||||
Output: ["a","b","c"]
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
0 <= digits.length <= 4
|
||||
digits[i] is a digit in the range ['2', '9'].
|
Loading…
Reference in new issue