常见算法 - 根据输入数字按手机九建求可能组合成的字符串

根据输入数字按手机九建求可能组合成的字符串(leetcode17):

Given a string containing digits from 2-9 inclusive, 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 that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].


思路:按序拆分数字字符串,每个数字字符对应多个字符,所以要遍历对应的每个字符,拼接到结果字符串,在此基础上再遍历一个数字字符对应的每个字母字符,拼接到结果字符串上,这就是一个递归的过程,递归的出口就是遍历完所有的数字字符。如图所示:

当遍历到数字字符2时,对于其对应的每个字母字符,都要拼接到结果字符上(res)同时递归调用遍历下一个数字字符3,整个递归过程的出口就是数字字符已经遍历完了,即下标大于length。

class Solution {
    
     List<String> res = new ArrayList<String>();
    final static String[] letterMap = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    
    public List<String> letterCombinations(String digits) {
        if(digits.equals("")){
            return res;
        }
        return helper(digits,0,"");
    }
    
    //index 当前数字字符串下标
    public  List<String> helper(String digits, int index, String currStr){
        
        if(index == digits.length() ){
            res.add(currStr);
            return res;
        }
        //找到当前数字
        char c = digits.charAt(index);
        //找到当前数字对应的字符串
        String letter = letterMap[c-'0'];
        //挨个遍历、递归组合字符串
        for(int i = 0; i < letter.length(); i++){
            helper(digits, index+1, currStr+letter.charAt(i));
        }
        return res;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值