【LeetCode】56 电话号码的字母组合

|▌冷眼眸甩不掉的悲伤 提交于 2020-07-27 13:54:34

题目:

image-20200712200157957

image-20200712200143030

解题思路:

image-20200712200122390

代码:

package com.janeroad;

import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2020/7/12.
 *
 * [@author](https://my.oschina.net/arthor) LJN
 */
public class Test20 {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        int len = digits.length();
        if (len == 0) {
            return res;
        }

        String[] digitsMap = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

        // 注意:设置 res 的初始值为 ""
        res.add("");

        // 思路:新一轮在上一轮的基础末尾追加数字
        for (int i = 0; i < len; i++) {
            // 得到当前的数字,注意:这个偏移是 '2'
            int num = digits.charAt(i) - '2';
            String strList = digitsMap[num];
            List<String> cur = new ArrayList<>();
            for (String s : res) {
                for (char c : strList.toCharArray()) {
                    cur.add(s + c);
                }
            }
            res = cur;
        }
        return res;
    }

    public static void main(String[] args) {
        Test20 test20 = new Test20();
        List<String> list = test20.letterCombinations("23");
        list.forEach(item-> System.out.println(item));
    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!