1
+ import java .util .ArrayList ;
1
2
import java .util .LinkedList ;
2
3
import java .util .List ;
3
4
import java .util .Queue ;
@@ -8,54 +9,31 @@ public class LetterCombinationOfPhoneNumber {
8
9
* leetcode的测试用例中不包括包含"0"或"1"的情况
9
10
*/
10
11
11
- private final String [] ARR = {
12
+ private static final String [] ARR = {
12
13
"" , "" , "abc" , "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz"
13
14
};
14
15
15
- // 耗时3ms
16
+ // 耗时2ms
16
17
public List <String > letterCombinations (String digits ) {
17
- List <String > list = new LinkedList <>();
18
- if (! digits .isEmpty () ) {
19
- helper ( digits , 0 , list , "" ) ;
18
+ List <String > res = new ArrayList <>();
19
+ if (digits .length () == 0 ) {
20
+ return res ;
20
21
}
21
- return list ;
22
+ dfs (digits , new StringBuilder (), res , 0 );
23
+ return res ;
22
24
}
23
25
24
- private void helper (String digits , int start , List <String > list , String s ) {
26
+ private void dfs (String digits , StringBuilder sb , List <String > res , int start ) {
25
27
if (start >= digits .length ()) {
26
- list .add (s );
28
+ res .add (sb . toString () );
27
29
return ;
28
30
}
31
+
29
32
int n = digits .charAt (start ) - '0' ;
30
33
for (char c : ARR [n ].toCharArray ()) {
31
- helper (digits , start + 1 , list , s + c );
32
- }
33
- }
34
-
35
- /**
36
- * 非递归法,BFS,耗时5ms
37
- */
38
- public List <String > letterCombinations2 (String digits ) {
39
- LinkedList <String > queue = new LinkedList <String >();
40
- if (digits .length () == 0 ) {
41
- return queue ;
42
- }
43
-
44
- Queue <String > next = new LinkedList <>();
45
- queue .add ("" );
46
-
47
- for (int i = 0 ; i < digits .length () && !queue .isEmpty (); ) {
48
- String s = queue .poll ();
49
- int n = digits .charAt (i ) - '0' ;
50
- for (char c : ARR [n ].toCharArray ()) {
51
- next .add (s + c );
52
- }
53
- if (queue .isEmpty ()) {
54
- queue .addAll (next );
55
- next .clear ();
56
- i ++;
57
- }
34
+ sb .append (c );
35
+ dfs (digits , sb , res , start + 1 );
36
+ sb .setLength (sb .length () - 1 );
58
37
}
59
- return queue ;
60
38
}
61
39
}
0 commit comments