forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLetterCombinationsofaPhoneNumber.java
34 lines (26 loc) · 1.07 KB
/
LetterCombinationsofaPhoneNumber.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package medium;
import java.util.*;
/**
* Created by fishercoder1534 on 10/3/16.
*/
public class LetterCombinationsofaPhoneNumber {
public List<String> letterCombinations(String digits) {
String[] digits2Letters = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> result = new ArrayList();
if(digits.length() == 0) return result;
result.add("");//this line is important, otherwise result is empty and Java will default it to an empty String
for(int i = 0; i < digits.length(); i++){
result = combine(digits2Letters[digits.charAt(i)-'0'], result);
}
return result;
}
List<String> combine(String letters, List<String> result){
List<String> newResult = new ArrayList();
for(int i = 0; i < letters.length(); i++){//the order of the two for loops doesn't matter, you could swap them and it still works.
for(String str : result){
newResult.add(str + letters.charAt(i));
}
}
return newResult;
}
}