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.
Note: The toString() method of StringBuilder will return a newly allocated String object. In other word, it is a "deep copy" of the content in the StringBuilder instance.
-
toString
public String toString()
Returns a string representing the data in this sequence. A newString
object is allocated and initialized to contain the character sequence currently represented by this object. ThisString
is then returned. Subsequent changes to this sequence do not affect the contents of theString
.-
Specified by:
-
toString
in interfaceCharSequence
Returns:
- a string representation of this sequence of characters.
-
public class Solution {
public HashMap<Character, char[]> map = new HashMap<Character, char[]>();
public void constructMap() {
this.map.put('2', "abc".toCharArray());
this.map.put('3', "def".toCharArray());
this.map.put('4', "ghi".toCharArray());
this.map.put('5', "jkl".toCharArray());
this.map.put('6', "mno".toCharArray());
this.map.put('7', "pqrs".toCharArray());
this.map.put('8', "tuv".toCharArray());
this.map.put('9', "wxyz".toCharArray());
}
public void letterCombinations(String digits, int index, ArrayList<String> res, StringBuilder tem) {
if(index == digits.length()) {
res.add(tem.toString());
return;
}
char[] current = map.get(digits.charAt(index));
for(int i=0; i<current.length; i++) {
tem.append(current[i]);
letterCombinations(digits, index+1, res, tem);
tem.deleteCharAt(tem.length()-1);
}
return;
}
public ArrayList<String> letterCombinations(String digits) {
ArrayList<String> res = new ArrayList<String>();
StringBuilder tem = new StringBuilder();
constructMap();
letterCombinations(digits, 0, res, tem);
return res;
}
}