Algorithm Letter Combinations of a Phone Number
Description
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
Example
Input: "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.
Submission
package com.cctoken.algorithm;
import java.util.LinkedList;
import java.util.List;
/**
* @author chenchao
*/
public class LetterCombination {
public List<String> letterCombinations(String digits) {
String[] mapDigits = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> res = new LinkedList<String>();
if (digits.length() == 0) {
return res;
}
res.add("");
for (int i = 0; i < digits.length(); ++i) {
res = combineTwoString(mapDigits[digits.charAt(i) - '0' - 2], res);
}
return res;
}
// define a function that join the string and the previous result
// and return the list result
public List<String> combineTwoString(String left, List<String> prevStr) {
List<String> res = new LinkedList<String>();
for (String prev : prevStr) {
for (int i = 0; i < left.length(); ++i) {
res.add(prev + left.charAt(i));
}
}
return res;
}
public static void main(String[] args) {
String digits = "23";
List<String> res = new LetterCombination().letterCombinations(digits);
}
}
Solution
解题思路:手机九宫格按键,每个数字对应相应的字符,枚举出所有可能的结果。
我们首先定义一个转换函数,combineTwoString(函数名定义的不是很好),将第一个参数所有单个字符放在 prevStr 里的每个元素后面
规定起始参数 prevStr 为 ""