码迷,mamicode.com
首页 > 其他好文 > 详细

Letter Combinations of a Phone Number

时间:2015-07-03 23:23:10      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

1. Question

给一个数字字符串,按照电话上各个数字对应的字母,返回该字符串代表的所有可能的字母组合。

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"].

2. Solution(O(3n))

考虑特殊情况:

  • 空串

2.1 遍历法

依次遍历字符串中的每个数,寻找可能的组合。

技术分享
    public List<String> letterCombinations( String digits ){
        String[] map = { " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        int len = digits.length();
        LinkedList<String> res = new LinkedList<String>();
        if( len<1 )
            return res;
        res.add("");
        for( int i=0; i<len; i++ ){
            int now = digits.charAt( i ) - ‘0‘;
            if( now<2 )
                continue;
            char[] toInsert = map[now].toCharArray();
            while( res.peek().length() == i ) {
                String each = res.remove();
                for( int j=0; j<toInsert.length; j++ )
                    res.add( each + toInsert[j] );
            }
        }
        return res;
    }
View Code

2.2 树搜索法

对数字进行解析,相当于遍历一棵树,可以使用数的遍历算法

技术分享
public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        String[] map = new String[10];
        map[0] = "";
        map[1] = "";
        map[2] = "abc";
        map[3] = "def";
        map[4] = "ghi";
        map[5] = "jkl";
        map[6] = "mno";
        map[7] = "pqrs";
        map[8] = "tuv";
        map[9] = "wxyz";
        char[]    middleTemp = new char[digits.length()];
        dfsGetStr(digits, 0, middleTemp, map, result); 
        return result;
    }
    
    private void dfsGetStr(String digits,int index, 
            char[] middleStr, String[] map, List<String> result) {
        if(index == digits.length()) {
            result.add(new String(middleStr));
            return ;
        }
        char strChar = digits.charAt(index);
        for(int i=0; i<map[strChar-‘0‘].length(); i++) {
            middleStr[index] = map[strChar-‘0‘].charAt(i);
            dfsGetStr(digits, index+1, middleStr, map, result);
        }
    }
View Code

 

Letter Combinations of a Phone Number

标签:

原文地址:http://www.cnblogs.com/hf-cherish/p/4607097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!