lintcode-medium-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.
Given "23"
Return["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
public class Solution { /** * @param digits A digital string * @return all posible letter combinations */ public ArrayList<String> letterCombinations(String digits) { // Write your code here if(digits == null || digits.length() == 0) return new ArrayList<String>(); String[] strs = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; ArrayList<String> result = new ArrayList<String>(); StringBuilder line = new StringBuilder(); helper(result, line, 0, digits, strs); return result; } public void helper(ArrayList<String> result, StringBuilder line, int start, String digits, String[] strs){ if(start == digits.length()){ result.add(line.toString()); return; } int index = digits.charAt(start) - '0'; for(int i = 0; i < strs[index].length(); i++){ line.append(strs[index].charAt(i)); helper(result, line, start + 1, digits, strs); line.deleteCharAt(start); } return; } }