Skip to content

Commit

Permalink
fix 017 java
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Oct 3, 2023
1 parent 2cd6010 commit ab414c3
Showing 1 changed file with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,49 @@

public class LetterCombinationsOfAPhoneNumber {

// V0
List<String> _res = new ArrayList<String>();
public List<String> letterCombinations(String _digits) {

if (_digits.length() == 0){
return new ArrayList<>();
}

HashMap<java.lang.String, java.lang.String> letters = new HashMap<>();
letters.put("2", "abc");
letters.put("3", "def");
letters.put("4", "ghi");
letters.put("5", "jkl");
letters.put("6", "mno");
letters.put("7", "pqrs");
letters.put("8", "tuv");
letters.put("9", "wxyz");

_letter_builder(letters, 0, _digits, new StringBuilder());
return this._res;
}

private void _letter_builder(HashMap<String, String> map, int idx, String digits, StringBuilder builder){

if (builder.length() == digits.length()){
this._res.add(builder.toString()); // NOTE this
return;
}

String _digit = String.valueOf(digits.toCharArray()[idx]); // NOTE this
String _alphabets = map.get(_digit);

// backtrack
for (char a : _alphabets.toCharArray()){
builder.append(a);
_letter_builder(map, idx+1, digits, builder);
// undo
// builder.deleteCharAt(0); // NOTE !!! in backtrack, we remove LAST element (idx = len - 1), instead of first element
builder.deleteCharAt(builder.toString().length() - 1);
}
}


// V0
// IDEA : BACKTRACK
// public List<String> letterCombinations(String digits) {
Expand Down

0 comments on commit ab414c3

Please sign in to comment.