(Leetcode)17. Letter Combinations of a Phone Number——使用LinkedList

题目: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.

这里写图片描述

Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

算法思想:

每读入一个新的数字 , 比如 5,获得该数字对应的字符串数组strs,5对应的是{“j”,”k”,”l”}。将 result中的每一项取出,在后面分别加上j/k/l,将这新的三项加入result,并删除原来的项。

代码:

 public List<String> letterCombinations(String digits) {
        LinkedList<String> result = new LinkedList<String>();
        if(digits.equals(""))  return result;
        result.add("");
        String trans_function[][] = {
                {"0"},                // 0
                {"1"},                   // 1
                {"a","b","c"},        // 2
                {"d","e","f"},        // 3
                {"g","h","i"},        // 4        
                {"j","k","l"},        // 5
                {"m","n","o"},        // 6
                {"p","q","r","s"},    // 7
                {"t","u","v"},        // 8
                {"w","x","y","z"}     // 9
                };

        for(int i=0 ; i<digits.length(); i++){
            String strs[] = trans_function[digits.charAt(i)-'0'];

            while( result.peek().length()==i ){
                String head_str = result.remove();
                for( String ch: strs ){
                    result.add(head_str+ch);
                }
            }
        }

        return result;
    }

几个函数:

java.util.LinkedList:
双向列表,列表中的每个节点都包含了对前一个和后一个元素的引用.

peek()
Retrieves, but does not remove, the head (first element) of this list.
return :the head of this list, or null if this list is empty
remove()
Retrieves and removes the head (first element) of this list.
return : the head of this list
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值