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

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

    Note:
    Although the above answer is in lexicographical order, your answer could be in any order you want.

    算法:DFS。函数头是private void dfs(String digits, int idx, String[] map, StringBuilder crt, List<String> result) 

    每次对当前这个数字可能表示的几种字母for循环去尝试。

    细节:1.StringBuilder回溯的函数是sb.deleteCharAt(index)!!没有remove方法,只有delete(区间), deleteCharAt(位置)方法。 2.JAVA没有Integer.parseInt(Char)方法,可能是觉得char转int足够了就用c-'0'. 3.小心0,1的处理,不是就直接返回了,而是也要dfs下一个数字再返回。 4.出口不是看做出来的字符串的长度了,而是看现在遍历数字遍历完了没有

    实现:

    class Solution {
        public List<String> letterCombinations(String digits) {
            List<String> result = new ArrayList<>();
            if (digits == null || digits.length() == 0) {
                return result;
            }
    
            String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            dfs(digits, 0, map, new StringBuilder(), result);
            return result;
        }
    
        private void dfs(String digits, int idx, String[] map, StringBuilder crt, List<String> result) {
            if (idx >= digits.length() && crt.length() > 0) {
                result.add(crt.toString());
                return;
            }
    
            // Integer.parseInt居然神坑,不支持转char
            int digit =digits.charAt(idx) - '0';
            if (digit == 0 || digit == 1) {
                dfs(digits, idx + 1, map, crt, result);
                return;
            }
    
            String chars = map[digit];
            for (int i = 0; i < chars.length(); i++) {
                crt.append(chars.charAt(i));
                dfs(digits, idx + 1, map, crt, result);
                crt.deleteCharAt(crt.length() - 1);
            }
    
        }
    }
  • 相关阅读:
    python3数据库配置,远程连接mysql服务器
    Ubuntu 16.04安装JDK
    用Python从零开始创建区块链
    理解奇异值分解SVD和潜在语义索引LSI(Latent Semantic Indexing)
    gensim介绍(翻译)
    记一次浅拷贝的错误
    Heap queue algorithm
    Python
    python列表中插入字符串使用+号
    Linux(Ubuntu)使用 sudo apt-get install 命令安装软件的目录在哪?
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7983291.html
Copyright © 2011-2022 走看看