425 - 电话号码的字母组合

本文详细解析了一个关于电话号码字母组合的算法实现过程。通过三个嵌套循环,结合特定的字符串映射关系,该算法能够生成所有可能的字母组合。文章提供了完整的Java代码示例,并介绍了如何处理组合过程中出现的有效性和效率问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

5.17

这个题目思路上并不难,但是实现起来,我用了很多的时间,主要还是自己的思路不是特别清晰吧。

用到了三个循环

for(第一个数字 to 最后一个数字){

    for( 数字对应的第一个字母 to 最后一个字母){

        for(Arraylist中的第一个元素 to 最后一个元素){

                 Arraylist.add();

        }

    }

    这里要对Arraylist进行操作,删除无效的部分

}

public class Solution {
    /**
     * @param digits A digital string
     * @return all posible letter combinations
     */
    public ArrayList<String> letterCombinations(String digits) {
        // Write your code here
        String[] nums = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        ArrayList<String> res = new ArrayList<String>();
        int count = 1;
        int length = digits.length();
        for(int i = 0; i < length ; i++){
            // num 表示第i位的数字的值
            int num = digits.charAt(i) - '0';
            // sizeNum表示,这个数字对应的字符串的长度
            int sizeNum = nums[num].length();
            if(res.isEmpty()){
                for(int j = 0; j < sizeNum ; j++){
                    //System.out.println("nums[i]:" + nums[num] +";i:" + i + ";j:" + j);
                    res.add(Character.toString(nums[num].charAt(j)));
                    
                }
                count = sizeNum;
                continue;
            }
            else{
                int resSize = res.size();
                for(int j = 0; j < sizeNum ; j++){
                    for(int k = 0; k < resSize;k++){
                        String s = res.get(k) + Character.toString(nums[num].charAt(j));
                        res.add(s);
                    }
                }
            }
            if(!res.isEmpty()){
                int resSize = res.size();
                //System.out.println("resSize:" + res.size() + "; count:" + count);
                //System.out.println("res前" + res);
                for(int h = 0;h < count;h++){
                    res.remove(0);
                }
                //System.out.println("res后" + res);
            }
            count = count * sizeNum;
        }
       return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值