2
2
3
3
import io .github .spannm .leetcode .LeetcodeProblem ;
4
4
5
- import java .util .*;
6
- import java .util .stream .IntStream ;
5
+ import java .util .ArrayList ;
6
+ import java .util .Collection ;
7
+ import java .util .HashSet ;
8
+ import java .util .List ;
7
9
8
10
/**
9
11
* <a href="https://leetcode.com/problems/letter-combinations-of-a-phone-number/">17. Letter Combinations of a Phone
10
12
* Number</a>.
11
13
*/
12
14
class Problem0017 extends LeetcodeProblem {
13
15
14
- @ SuppressWarnings ("unchecked" )
15
- private static final List <String >[] DIGITS_TO_LETTERS = new List [] {null , // 0
16
- null , // 1
17
- List .of ("a" , "b" , "c" ), // 2
18
- List .of ("d" , "e" , "f" ), // 3
19
- List .of ("g" , "h" , "i" ), List .of ("j" , "k" , "l" ), List .of ("m" , "n" , "o" ), List .of ("p" , "q" , "r" , "s" ), List .of ("t" , "u" , "v" ), List .of ("w" , "x" , "y" , "z" )
20
- };
21
-
22
16
private static final char [][] DIGITS_TO_CHARS = new char [][] {null , // 0
23
17
null , // 1
24
18
{'a' , 'b' , 'c' }, // 2
25
19
{'d' , 'e' , 'f' }, // 3
26
20
{'g' , 'h' , 'i' }, {'j' , 'k' , 'l' }, {'m' , 'n' , 'o' }, {'p' , 'q' , 'r' , 's' }, {'t' , 'u' , 'v' }, {'w' , 'x' , 'y' , 'z' }
27
21
};
28
22
29
- public List <String > letterCombinations (String _digits ) {
23
+ List <String > letterCombinations (String _digits ) {
30
24
if (_digits == null || _digits .isEmpty ()) {
31
25
return List .of ();
32
26
}
@@ -48,40 +42,4 @@ static Collection<String> cartesianProduct(String _input, StringBuilder _sb, int
48
42
return _product ;
49
43
}
50
44
51
- public List <String > letterCombinations2 (String _digits ) {
52
- final int len = _digits .length ();
53
-
54
- if (len == 0 ) {
55
- return List .of ();
56
- }
57
-
58
- List <List <String >> lol = IntStream .range (0 , len )
59
- // .map(i -> digits.charAt(i) - '0')
60
- .map (i -> Character .getNumericValue (_digits .charAt (i )))
61
- .mapToObj (i -> DIGITS_TO_LETTERS [i ])
62
- .toList ();
63
-
64
- if (len == 1 ) {
65
- return lol .get (0 );
66
- }
67
-
68
- Set <String > combinations = new LinkedHashSet <>();
69
-
70
- generatePermutations (lol , combinations , 0 , "" );
71
-
72
- return new ArrayList <>(combinations );
73
- }
74
-
75
- // cartesian product
76
- void generatePermutations (List <List <String >> _lists , Collection <String > _result , int _depth , String _current ) {
77
- if (_depth == _lists .size ()) {
78
- _result .add (_current );
79
- return ;
80
- }
81
-
82
- for (String element : _lists .get (_depth )) {
83
- generatePermutations (_lists , _result , _depth + 1 , _current + element );
84
- }
85
- }
86
-
87
45
}
0 commit comments