Easy to understand the solution


  • 0
    V

    public List<String> letterCombinations(String digits) {

        //bug1: 数组下标越界,因为少了个元素
        String[] letterArray = new String[]{" ", "", "abc", "def", "ghi","jkl", "mno", "pqrs", "tuv", "wxyz"};
        StringBuffer solution = new StringBuffer();
        List<String> result = new ArrayList<>();
        if (digits == null || digits.length() == 0) return result;
        char[] digitArray = digits.toCharArray();
        buildUpCombinations(result, solution, letterArray, digitArray, 0);
    
        return result;
    
    }
    
    private void buildUpCombinations(List<String> result, StringBuffer solution, String[] letterArray,
                                     char[] digitArray, int index) {
        if (index == digitArray.length) {
            result.add(solution.toString());
            return;
        }
        int tmpIndex = digitArray[index] - '0';
        if (tmpIndex == 1) {
            buildUpCombinations(result, solution, letterArray, digitArray, index + 1);
    
        } else {
    
            for (char c : letterArray[tmpIndex].toCharArray()) {
                solution.append(c);
                buildUpCombinations(result, solution, letterArray, digitArray, index + 1);
                solution.deleteCharAt(solution.length() - 1);
            }
    
        }
    }

Log in to reply
 

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