zoukankan      html  css  js  c++  java
  • [LeetCode] 17. Letter Combinations of a Phone Number ☆☆

    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.

    phone numbers

    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.

    解法1: 

      采用队列的方法,遍历digits的每一位数字,对于遍历到的数字,将队列中所有的字符串从头部移除,加上当前数字对应的字母后依次添加到队列后端。

    public class Solution {
        public List<String> letterCombinations(String digits) {
            List<String> res = new ArrayList<>();
            
            if (digits == null || digits.length() == 0) {
                return res;
            }
            
            String[] letters = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            res.add("");
            
            for (int i = 0; i < digits.length(); i++) {
                int size = res.size();
                String str = letters[digits.charAt(i) - '2'];
                for (int j = 0; j < size; j++) {
                    String front = res.remove(0);  // 不是remove(j),每次都应该移除第一个字符串
                    for (int k = 0; k < str.length(); k++) {
                        res.add(front + str.charAt(k));
                    }
                }
            }
            return res;
        }
    }

    解法2: 

      采用递归的方法,每次添加一个字母后进行下一次递归:

    public class Solution {
        public List<String> letterCombinations(String digits) {
            List<String> res = new ArrayList<>();
            
            if (digits == null || digits.length() == 0) {
                return res;
            }
            
            String[] letters = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "utv", "wxyz"};
            helper(res, letters, digits, "");
            return res;
        }
        
        public void helper(List<String> res, String[] letters, String digits, String temp) {
            if (digits.length() == 0) {
                res.add(temp);
                return;
            }
            String str = letters[digits.charAt(0) - '2'];
            for (int i = 0; i < str.length(); i++) {
                helper(res, letters, digits.substring(1), temp + str.charAt(i));
            }
        }
    }

    解法2: 

  • 相关阅读:
    Superset 制作图表
    superset 安装配置
    python 虚拟环境 pyenv
    pymysql 单独获取表的栏位名称
    pymysql 返回数据为字典形式(key:value--列:值)
    Oracle/MySQL decimal/int/number 转字符串
    netstat 问题处理
    MySQL 中Index Condition Pushdown (ICP 索引条件下推)和Multi-Range Read(MRR 索引多范围查找)查询优化
    MySQL执行计划extra中的using index 和 using where using index 的区别
    ref与out
  • 原文地址:https://www.cnblogs.com/strugglion/p/6410210.html
Copyright © 2011-2022 走看看