Monday, February 10, 2014

Letter Combinations of a Phone Number @LeetCode


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"].
package leetcode.combinations;
import java.util.ArrayList;
/**
* Character.getNumericValue("23".charAt(0)); --> Get int value From different digit of string
* Difference from subsets --- not just one array.
*
* Solution: use index to control char group -- useful
* Because char in every group is unique, we don't need flag position to control ordering like other combination problems.
* We only need to care how to map in differnt groups, we use sb.toString() here.
* sb.toString() = 0, get index 0 of digits, --> 2, so select char[2] group.
*
* We could also use Hashmap instead of char[][]
*
* @author jeffwan
* @date Feb 10, 2014 Refactor April.10
*/
public class LetterCombinations {
char[][] map = {{}, {}, {'a','b','c'}, {'d','e','f'}, {'g','h','i'}, {'j','k','l'}, {'m','n','o'},
{'p','q','r','s'}, {'t','u','v'}, {'w','x','y','z'}};
public ArrayList<String> letterCombinations(String digits) {
ArrayList<String> result = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
helper(result, sb, digits);
return result;
}
private void helper(ArrayList<String> result, StringBuffer sb,
String digits) {
if (sb.length() == digits.length()) {
result.add(sb.toString());
return;
}
int index = Character.getNumericValue(digits.charAt(sb.length()));
for (int i = 0; i < map[index].length; i++) {
sb.append(map[index][i]);
helper(result, sb, digits);
sb.deleteCharAt(sb.length() - 1);
}
}
/**
Map<Character, char[]> map = new HashMap<Character, char[]>();
map.put('0', new char[] {});
map.put('1', new char[] {});
map.put('2', new char[] { 'a', 'b', 'c' });
map.put('3', new char[] { 'd', 'e', 'f' });
map.put('4', new char[] { 'g', 'h', 'i' });
map.put('5', new char[] { 'j', 'k', 'l' });
map.put('6', new char[] { 'm', 'n', 'o' });
map.put('7', new char[] { 'p', 'q', 'r', 's' });
map.put('8', new char[] { 't', 'u', 'v'});
map.put('9', new char[] { 'w', 'x', 'y', 'z' });
for (char c : map.get(digits.charAt(sb.length()))) {
sb.append(c);
helper(map, digits, sb, result);
sb.deleteCharAt(sb.length() - 1);
}
*/
}

No comments:

Post a Comment