LeetCode 17 Letter Combinations of a Phone Number

来源:互联网 发布:ucloud云计算 2016 09 编辑:程序博客网 时间:2024/06/10 11:51

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

这里写图片描述

Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

解决

class Solution {   static String[][] numbers = new String[][] { {""}, {""}, { "a", "b", "c" }, { "d", "e", "f" }, { "g", "h", "i" },            { "j", "k", "l" }, { "m", "o", "n" }, { "p", "q", "r", "s" }, { "t", "u", "v" }, { "w", "x", "y", "z" } };             public List<String> letterCombinations(String digits) {        List<String> rList = new ArrayList<>();        int number = 0;        if (digits.length() > 1) {            number = Integer.valueOf(digits.substring(0, 1));            List<String> subList = letterCombinations(digits.substring(1));            String[] strings = numbers[number];            for (int i = 0; i < strings.length; i++) {                String mLetter = strings[i];                for (String str : subList) {                    rList.add(mLetter + str);                }            }        } else if (digits.length() == 1) {            number = Integer.valueOf(digits);            String[] words = numbers[number];            for (int i = 0; i < words.length; i++) {                rList.add(words[i]);            }        }        return rList;    }}
阅读全文
0 0
原创粉丝点击