电话字母的组合

电话字母的组合

http://www.nowcoder.com/questionTerminal/5044a44afe6c40ec9b67b7531393e854

利用队列求解

public ArrayList<String> letterCombinations(String digits) {
    ArrayList<String> res = new ArrayList<String>();
    HashMap<Character, String> dict = new HashMap<Character, String>();
    dict.put('2', "abc");
    dict.put('3', "def");
    dict.put('4', "ghi");
    dict.put('5', "jkl");
    dict.put('6', "mno");
    dict.put('7', "pqrs");
    dict.put('8', "tuv");
    dict.put('9', "wxyz");
    Queue<String> queue = new LinkedList<String>();
    // 先往队列中加入一个空字符串,以便和digits的第一个字符进行拼接
    queue.offer("");
    // 遍历数字字符串,
    for (char c : digits.toCharArray()) {
        // 当前数字对应的字母列表
        String words = dict.get(c);
        // 计算队列长度
        int n = queue.size();
        for (int i = 0; i < n; i++) {
            // 每次从队列取出一个元素,并和当前words中每一个字母进行拼接
            String cur = queue.poll();
            for (int j = 0; j < words.length(); j++) {
                queue.offer(cur + words.charAt(j));
            }
        }
    }
    res.addAll(queue);
    return res;
}

注:dict也可以用字符串数组来表示

全部评论

相关推荐

不愿透露姓名的神秘牛友
04-30 11:43
春招失败、父母离婚,好像我的人生一团糟,一年来压力大到常常崩溃。不知道能跟谁聊,朋友其实对我非常好,但是她无意中表达出来的家庭幸福都会刺痛到我……和ai聊天,我的未来在更高处,不在楼下,忍不住爆哭😭
youngfa:害,妹妹,我是一个研究生(很上进很想找到好工作的那种),但去年因为生病回家休养错过了秋招(当时对我的冲击也是非常大的),这学期返校来了也是把论文盲审交了后才开始找工作,现在也是一个offer没有,但我就没有像你一样把这个阶段性的事情绑定到人生上,人生不仅很长,也很广阔,先停下来,放松一下哦。不要被外部环境灌输的思维操控了,好好爱自己!
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客企业服务