【小熊刷題】Letter Combinations of a Phone Number

Question

iven 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.

*Difficulty: Medium
https://leetcode.com/problems/letter-combinations-of-a-phone-number/

My Solution

public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> list = new ArrayList<String>();

        HashMap<Character, String> map = new HashMap<>();
        map.put('1',""); 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"); map.put('0'," ");

        for(char c : digits.toCharArray()){
            String s = map.get(c);
            if(list.isEmpty()){
                for(char a : s.toCharArray()){
                    list.add(""+a);   
                }
            }else{
                int count = list.size();
                while(count > 0){
                    String l = list.remove(0);
                    for(char a : s.toCharArray()){
                        list.add(l+a);
                    }
                    count--;
                }
            }
        }

        return list;
    }


}

Backtracking (Recursive) Solution

public class Solution {
    public List<String> letterCombinations(String digits) {
        ArrayList<String> res = new ArrayList<String>();
        String[] keyboard = new String[]{" ","","abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        letterCombinationsRe(keyboard,res,digits,"");
        return res;
    }
    public void letterCombinationsRe(String[] keyboard, ArrayList<String> res, String digits, String s) {
        if (s.length() == digits.length()) {
            res.add(s);
            return;
        }
        String letters = keyboard[digits.charAt(s.length()) - '0'];
        for (int i = 0; i < letters.length(); ++i) {
            letterCombinationsRe(keyboard, res, digits, s+letters.charAt(i));
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章