代码改变世界

LeetCode 17. Letter Combinations of a Phone Number

2019-05-26 22:13  yx1989  阅读(127)  评论(0编辑  收藏  举报

比较简单的一道题,循环搞定

Runtime: 0 ms
Memory Usage: 2.6 MB

import (
	"fmt"
	"strconv"
)

func letterCombinations(digits string) []string {
	var result []string
	if len(digits) == 0 {
		return result
	}

	i2a := initMapping()
	result = append(result, "")
	for i := 0; i < len(digits); i++ {
		num, _ := strconv.Atoi(digits[i : i+1])

		var tmpResult []string

		for _, x := range result {
			for _, y := range i2a[num] {
				tmpResult = append(tmpResult, x+y)
			}
		}


		result = tmpResult
	}
	return result
}

func initMapping() map[int][]string {
	i2a := make(map[int][]string)
	i2a[2] = [] string{"a", "b", "c"}
	i2a[3] = [] string{"d", "e", "f"}
	i2a[4] = [] string{"g", "h", "i"}
	i2a[5] = [] string{"j", "k", "l"}
	i2a[6] = [] string{"m", "n", "o"}
	i2a[7] = [] string{"p", "q", "r", "s"}
	i2a[8] = [] string{"t", "u", "v"}
	i2a[9] = [] string{"w", "x", "y", "z"}
	return i2a
}