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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Solution:
Trivial implementation question.
Tips: 7 and 9 have four letters.
Although the above answer is in lexicographical order, your answer could be in any order you want.
Solution:
Trivial implementation question.
Tips: 7 and 9 have four letters.
public class Solution {
public ArrayList letterCombinations(String digits) {
String[] map = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; // 2 -> 0
ArrayList prev = new ArrayList();
prev.add("");
for(int i = 0; i < digits.length(); i++){
ArrayList cur = new ArrayList();
// all combinations
char[] tmp = map[digits.charAt(i) - '0' - 2].toCharArray();
for(String str : prev){
for(char c : tmp){
cur.add(str+c);
}
}
prev = cur;
}
return prev;
}
}
No comments:
Post a Comment