My concise java solution


  • 2
    H
    private final char[][] INT_TO_LETTER = {{' '}, {' '}, {'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'}};
    private List<String> result = new ArrayList<String>();
    
    public List<String> letterCombinations(String digits) {
    	if (digits != null && digits.length() != 0)  helper("", digits);
    	return result;
    }
    
    private void helper(String s, String digits) {
        if (digits.length() == 0) {result.add(s); return;}
        for (char l : INT_TO_LETTER[digits.charAt(0) - '0'])
            helper(s + l, digits.substring(1));
    }

  • 0
    N

    A little comment

    Instead of the trim "d.substring(1)"
    I think add a parameter as the index of 'd' is better

    private void letter(List<String> output, String d, String ch, int len, int index)

    String[] s =intToLetter[Integer.parseInt(d.charAt(index))];
    for (int i = 0; i < s.length; i++)
    letter(output, d, ch + s[i], len,index+1);


  • 0
    H

    Thanks for your comment! But the method Integer.parseInt(String) is not applicable for arguments (char), so Integer.parseInt(d.charAt(index)) will hava a compile error.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.