Last active
October 9, 2018 04:02
-
-
Save hsaputra/fea6a827cb022c14ac836a44429f7006 to your computer and use it in GitHub Desktop.
Phone number combo - interview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public List<String> letterCombinations(String digits) { | |
if (digits == null || digits.length() == 0) | |
return new LinkedList<String>(); | |
// local vars | |
Map<Integer, String> digitsToChars = new HashMap<Integer, String>(); | |
digitsToChars.put(0, ""); | |
digitsToChars.put(1, ""); | |
digitsToChars.put(2, "abc"); | |
digitsToChars.put(3, "def"); | |
digitsToChars.put(4, "ghi"); | |
digitsToChars.put(5, "jkl"); | |
digitsToChars.put(6, "mno"); | |
digitsToChars.put(7, "pqrs"); | |
digitsToChars.put(8, "tuv"); | |
digitsToChars.put(9, "wxyz"); | |
List<String> combos = new LinkedList<String>(); | |
List<Character> prefix = new LinkedList<Character>(); | |
char[] digitChars = digits.toCharArray(); | |
permutate(combos, prefix, 0, digitChars, digitsToChars); | |
return combos; | |
} | |
private void permutate(final List<String> combos, final List<Character> prefix, int curIndex, | |
final char[] digitChars, final Map<Integer, String> digitsToChars) { | |
// Stopping condition | |
if (curIndex == digitChars.length) { | |
StringBuilder builder = new StringBuilder(); | |
for (Character charElem : prefix) { | |
builder.append(charElem); | |
} | |
combos.add(builder.toString()); | |
return; | |
} | |
// Else permutate. | |
System.out.println("Current Digit char " + digitChars[curIndex]); | |
int curDigit = digitChars[curIndex] - '0'; | |
System.out.println("Current Digit " + curDigit); | |
char[] charsForDigit = (digitsToChars.get(curDigit)).toCharArray(); | |
System.out.println("Chars in Digit " + new String(charsForDigit)); | |
for (char charInDigit : charsForDigit) { | |
System.out.println("Char in Digit " + charInDigit); | |
prefix.add(charInDigit); | |
System.out.println("Chars in Prefix " + prefix); | |
permutate(combos, prefix, curIndex + 1, digitChars, digitsToChars); | |
int removeIndex = prefix.size() - 1; | |
prefix.remove(removeIndex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment