Leetcode--17:Letter Combinations of a Phone Number

来源:互联网 发布:软件招商加盟政策 编辑:程序博客网 时间:2024/06/11 06:03

Question:
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.
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

给定一个数字字符串,返回该数字所代表的所有可能的字母组合。
下面给出了一个数字到字母的映射(就像电话按钮一样)。
这里写图片描述
虽然上述的答案是在字典顺序,但是你的答案可以是任意顺序。

样例输入: 数字字符串“23”
样例输出: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]

Answer:
字母排列组合,函数递归可以求解。

import java.util.ArrayList;import java.util.Collections;import java.util.List;public class Solution {/*    digits为数字字符串;    count为当前获取到的数字字符下标    s 为动态字符串,用来动态获取最后添加到list数组中的字符串    result 为字符串数组    strs 为各个数字代表的字符数组*/    void getLetterCombinations(String digits, int count, StringBuilder s, List<String> result, String strs[]){        if(count==digits.length()){            String ss = new String(s);            result.add(ss);            return ;        }        int num = digits.charAt(count)-48;        for(int i=0; i<strs[num].length(); i++){            s.append(strs[num].charAt(i));            getLetterCombinations(digits,count+1,s,result,strs);            s.deleteCharAt(s.length()-1);        }    }    public List<String> letterCombinations(String digits){        if(digits.equals("")) return Collections.emptyList();//这一步不能写digits==""。同时这一步不能省略,否则提交之后输出为[""]。        String strs[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};        List<String> result = new ArrayList<>();        StringBuilder s = new StringBuilder();        getLetterCombinations(digits,0,s,result,strs);        return result;    }}

参考:http://blog.csdn.net/sbitswc/article/details/20022765

阅读全文
0 0