1
1
class Solution {
2
2
public List <String > letterCombinations (String digits ) {
3
- char [] cs = digits .toCharArray ();
4
- List <String > result = new ArrayList <>();
5
- for (char a : cs ) {
6
- char [] charArray ;
7
- switch (a ) {
8
- case '2' : charArray = new char []{'a' ,'b' ,'c' }; break ;
9
- case '3' : charArray = new char []{'d' ,'e' ,'f' }; break ;
10
- case '4' : charArray = new char []{'g' ,'h' ,'i' }; break ;
11
- case '5' : charArray = new char []{'j' ,'k' ,'l' }; break ;
12
- case '6' : charArray = new char []{'m' ,'n' ,'o' }; break ;
13
- case '7' : charArray = new char []{'p' ,'q' ,'r' ,'s' }; break ;
14
- case '8' : charArray = new char []{'t' ,'u' ,'v' }; break ;
15
- case '9' : charArray = new char []{'w' ,'x' ,'y' ,'z' }; break ;
16
- default : return null ;
17
- }
18
- if (result .size () == 0 ) {
19
- for (char aCharArray : charArray ) result .add (String .valueOf (aCharArray ));
3
+ int n ;
4
+ if ((n = digits .length ()) == 0 ) return Collections .emptyList ();
5
+ List <String > chars = Arrays .asList ("abc" , "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz" );
6
+
7
+ List <String > strs = new ArrayList <>();
8
+ for (char c : digits .toCharArray ()) {
9
+ strs .add (chars .get (c - '0' - 2 ));
10
+ }
11
+ List <String > res = new ArrayList <>();
12
+ for (String str : strs ) {
13
+ if (res .size () == 0 ) {
14
+ for (char c : str .toCharArray ()) {
15
+ res .add (String .valueOf (c ));
16
+ }
20
17
} else {
21
18
List <String > cache = new ArrayList <>();
22
- for (String string : result ) {
23
- for (char aCharArray : charArray ) cache .add (string + aCharArray );
19
+ for (String item : res ) {
20
+ for (char c : str .toCharArray ()) {
21
+ cache .add (item + String .valueOf (c ));
22
+ }
24
23
}
25
- result = cache ;
24
+ res = cache ;
26
25
}
27
26
}
28
- return result ;
27
+ return res ;
29
28
}
30
- }
29
+ }
0 commit comments