Skip to content

Commit 72327ad

Browse files
letter combinations of a phone number
1 parent 2566a8f commit 72327ad

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package medium;
2+
import java.util.*;
3+
/**
4+
* Created by fishercoder1534 on 10/3/16.
5+
*/
6+
public class LetterCombinationsofaPhoneNumber {
7+
8+
public List<String> letterCombinations(String digits) {
9+
String[] digits2Letters = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
10+
11+
List<String> result = new ArrayList();
12+
if(digits.length() == 0) return result;
13+
14+
result.add("");//this line is important, otherwise result is empty and Java will default it to an empty String
15+
for(int i = 0; i < digits.length(); i++){
16+
result = combine(digits2Letters[digits.charAt(i)-'0'], result);
17+
}
18+
19+
return result;
20+
}
21+
22+
List<String> combine(String letters, List<String> result){
23+
List<String> newResult = new ArrayList();
24+
25+
for(int i = 0; i < letters.length(); i++){
26+
for(String str : result){
27+
newResult.add(str + letters.charAt(i));
28+
}
29+
}
30+
31+
return newResult;
32+
}
33+
34+
}

0 commit comments

Comments
 (0)