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);
            }
    
        }
    }
  • 相关阅读:
    访问前端项目时Http请求变成了HTTPS
    Jenkins升级后无法正常启动(java.lang.IllegalStateException: An attempt to save the global configuration ......
    准备开始学习了。
    Nginx的安装与使用
    Linux 学习001
    Nginx为什么比Apache Httpd高效:原理篇
    Asp .Net Core Spa (二)
    Asp .Net Core Spa (一)
    基础笔记(三):网络协议之Tcp、Http
    跨平台运行ASP.NET Core 1.0
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7983291.html
Copyright © 2011-2022 走看看