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.
Although the above answer is in lexicographical order, your answer could be in any order you want.
Solution:
public class Solution { public ArrayList<String> letterCombinations(String digits) { ArrayList<String> previous = new ArrayList<String>(); previous.add(""); ArrayList<String> actual; for(int i=0; i<digits.length(); i++) { actual = new ArrayList<String>(); for(String s: previous) { switch (digits.charAt(i)) { case '2': actual.add(s+"a"); actual.add(s+"b"); actual.add(s+"c"); break; case '3': actual.add(s+"d"); actual.add(s+"e"); actual.add(s+"f"); break; case '4': actual.add(s+"g"); actual.add(s+"h"); actual.add(s+"i"); break; case '5': actual.add(s+"j"); actual.add(s+"k"); actual.add(s+"l"); break; case '6': actual.add(s+"m"); actual.add(s+"n"); actual.add(s+"o"); break; case '7': actual.add(s+"p"); actual.add(s+"q"); actual.add(s+"r"); actual.add(s+"s"); break; case '8': actual.add(s+"t"); actual.add(s+"u"); actual.add(s+"v"); break; case '9': actual.add(s+"w"); actual.add(s+"x"); actual.add(s+"y"); actual.add(s+"z"); break; } } previous = actual; } return previous; } }
No comments :
Post a Comment