2
2
3
3
import java .util .ArrayList ;
4
4
import java .util .HashMap ;
5
- import java .util .HashSet ;
6
5
import java .util .List ;
7
- import java .util .Set ;
8
6
9
7
/**
8
+ * 140. Word Break II
9
+ *
10
10
* Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
11
11
12
12
Return all such possible sentences.
19
19
20
20
*/
21
21
public class _140 {
22
- public List <String > wordBreak (String s , Set <String > wordDict ) {
23
- return dfs (s , wordDict , new HashMap <String , ArrayList < String > >());
22
+ public List <String > wordBreak (String s , List <String > wordDict ) {
23
+ return dfs (s , wordDict , new HashMap <>());
24
24
}
25
25
26
- private List <String > dfs (String s , Set <String > wordDict ,
27
- HashMap <String , ArrayList <String >> map ) {
26
+ List <String > dfs (String s , List <String > wordDict , HashMap <String , List <String >> map ) {
28
27
if (map .containsKey (s )) {
29
28
return map .get (s );
30
29
}
31
30
32
- ArrayList <String > res = new ArrayList <String >();
31
+ ArrayList <String > result = new ArrayList <>();
33
32
if (s .length () == 0 ) {
34
- res .add ("" );
35
- return res ;
33
+ result .add ("" );
34
+ return result ;
36
35
}
37
36
38
37
for (String word : wordDict ) {
39
38
if (s .startsWith (word )) {
40
39
List <String > subList = dfs (s .substring (word .length ()), wordDict , map );
41
40
for (String sub : subList ) {
42
- res .add (word + (sub .length () == 0 ? "" : " " ) + sub );
41
+ result .add (word + (sub .length () == 0 ? "" : " " ) + sub );
43
42
}
44
43
}
45
44
}
46
- map .put (s , res );
47
- return res ;
45
+ map .put (s , result );
46
+ return result ;
48
47
}
49
48
50
- public static void main (String ... strings ) {
51
- List <String > temp = new ArrayList <String >();
52
- System .out .println (temp );
53
- List <String > temp2 = new ArrayList <String >(temp );
54
- temp2 .add ("" );
55
- System .out .println (temp2 );
56
-
57
- _140 test = new _140 ();
58
- Set <String > wordDict = new HashSet ();
59
- wordDict .add ("cat" );
60
- wordDict .add ("cats" );
61
- wordDict .add ("sand" );
62
- wordDict .add ("and" );
63
- wordDict .add ("dog" );
64
- String s = "catsanddog" ;
65
- // List<String> list = test.wordBreak(s, wordDict);
66
- List <String > list = test .wordBreak (s , wordDict );
67
- for (String word : list ) {
68
- System .out .print (word + ", " );
69
- }
70
- System .out .println ();
71
- }
72
- }
49
+ }
0 commit comments