LeetCode题解:Letter Combinations of a Phone Number

来源:互联网 发布:windows bitlocker 编辑:程序博客网 时间:2024/05/16 19:04

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”].

题意:求给定字符串,按照给定映射关系能得到的所有字符组合

解题思路:用数组装每一个按键对应的可选字符,然后根据输入一一组合

代码:

public class Solution {    private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };    public List<String> letterCombinations(String digits) {        List<String> ret = new LinkedList<String>();        if(digits.length() == 0){            return ret;        }        combination("", digits, 0, ret);        return ret;    }    private void combination(String prefix, String digits, int offset, List<String> ret) {        if (offset >= digits.length()) {            ret.add(prefix);            return;        }        String letters = KEYS[(digits.charAt(offset) - '0')];        for (int i = 0; i < letters.length(); i++) {            combination(prefix + letters.charAt(i), digits, offset + 1, ret);        }    }}
0 0
原创粉丝点击