17. Letter Combinations of a Phone Number

来源:互联网 发布:淘宝小码鞋店 编辑:程序博客网 时间:2024/06/01 09:56

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

一刷ac
解题思路:利用递归的方法可以,采用前一段字符串来生成当前字符串的映射;非递归可以用队列存结果,每次利用队头生成新的结果。

public class Solution {    public List<String> letterCombinations(String digits) {        List<String> res = new ArrayList<String>();        if(digits == null || digits.length() == 0) return res;        char[] chars = digits.toCharArray();        HashMap<Character, String> map = new HashMap<Character, String>();        map.put('2', "abc");        map.put('3', "def");        map.put('4', "ghi");        map.put('5', "jkl");        map.put('6', "mno");        map.put('7', "pqrs");        map.put('8', "tuv");        map.put('9', "wxyz");        if(chars.length == 1){            String tmp = map.get(chars[0]);            for(int i = 0; i < tmp.length(); i++){                res.add(String.valueOf(tmp.charAt(i)));            }            return res;        }        String oldstr = digits.substring(0, digits.length()-1);        List<String> oldres = letterCombinations(oldstr);        String laststr = map.get(chars[chars.length-1]);        for(String s : oldres){            for(int i = 0; i < laststr.length(); i++){                String tmp = s;                tmp = tmp + laststr.charAt(i);                res.add(tmp);            }        }        return res;    }}
public class Solution {    public List<String> letterCombinations(String digits) {        List<String> res = new ArrayList<String>();        if(digits == null || digits.length() == 0) return res;        LinkedList<String> queue = new LinkedList<String>();        queue.offer("");        HashMap<Character, String> map = new HashMap<Character, String>();        map.put('2', "abc");        map.put('3', "def");        map.put('4', "ghi");        map.put('5', "jkl");        map.put('6', "mno");        map.put('7', "pqrs");        map.put('8', "tuv");        map.put('9', "wxyz");        for(int i = 0; i < digits.length(); i++){            String str = map.get(digits.charAt(i));            int size = queue.size();            for(int j = 0; j < size; j++){                String s = queue.pollFirst();                for(int k = 0; k < str.length(); k++){                    String tmp = s + str.charAt(k);                    queue.offer(tmp);                }            }        }        res.addAll(queue);        return res;    }}
0 0