Leetcode--17:Letter Combinations of a Phone Number

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值