zoukankan      html  css  js  c++  java
  • Letter Combinations of a Phone Number

    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
  • 相关阅读:
    Springboot构建问题集
    常用算法解析技巧总结
    Linux、Docker安装Nginx
    MySQL查询语句报错 sql_mode=only_full_group_by 问题
    MySQL按周统计 WEEK 实例
    IDEA注册码分享
    Mock测试接口
    Maven常用命令
    js中的for循环,循环次数会多出一次。当循环到最后一个的时候,循环还会继续,并且此时i就变成remove?
    vue .sync的理解
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4607097.html
Copyright © 2011-2022 走看看