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.


  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<String> res = new ArrayList<String>();
    
    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<String> 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<String> letterCombinations(String digits) {
        LinkedList<String> ans = new LinkedList<String>();
        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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容