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.

LeetCode 17 Letter Combinations of a Phone Number_第1张图片

   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.

代码实现

递归实现:24ms

import java.util.ArrayList;
import java.util.List;

public class Solution {
    char[][] letters = {
            {'a', 'b', 'c'},
            {'d', 'e', 'f'},
            {'g', 'h', 'i'},
            {'j', 'k', 'l'},
            {'m', 'n', 'o'},
            {'p', 'q', 'r', 's'},
            {'t', 'u', 'v'},
            {'w', 'x', 'y', 'z'}
    };  
    List res = new ArrayList();
    
    public void digui(String str, int[] digits, int start, int end) {   
        if (start == end+1) {
            res.add(str);
            return;
        }
        for (char letter : letters[digits[start]]) {
            String temp = str + String.valueOf(letter);
            digui(temp, digits, start+1, end);
        }
    }
    
    public List letterCombinations(String digits) {
        int[] digit = new int[digits.length()];
        for (int i = 0; i < digits.length(); i++) {
            digit[i] = digits.charAt(i) - 2 - '0';          
        }        
        digui("", digit, 0, digit.length-1);        
        return res;
    }
}

队列实现:1ms

import java.util.LinkedList;
import java.util.List;

public class Solution {
    public List letterCombinations(String digits) {
        LinkedList ans = new LinkedList();
        String[] mapping = new String[] { "0", "1", "abc", "def", "ghi", "jkl",
                "mno", "pqrs", "tuv", "wxyz" };
        ans.add("");
        for (int i = 0; i < digits.length(); i++) {
            int x = Character.getNumericValue(digits.charAt(i));
            while (ans.peek().length() == i) {
                String t = ans.remove();
                for (char s : mapping[x].toCharArray())
                    ans.add(t + s);
            }
        }
        return ans;
    }
}

你可能感兴趣的:(LeetCode 17 Letter Combinations of a Phone Number)