6
6
7
7
/**
8
8
* 140. Word Break II
9
- *
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
9
10
+ Given a non-empty string s and a dictionary wordDict containing a list of non-empty words,
11
+ add spaces in s to construct a sentence where each word is a valid dictionary word.
12
12
Return all such possible sentences.
13
13
14
- For example, given
15
- s = "catsanddog",
16
- dict = ["cat", "cats", "and", "sand", "dog"].
14
+ Note:
17
15
18
- A solution is ["cats and dog", "cat sand dog"].
16
+ The same word in the dictionary may be reused multiple times in the segmentation.
17
+ You may assume the dictionary does not contain duplicate words.
19
18
19
+ Example 1:
20
+
21
+ Input:
22
+ s = "catsanddog"
23
+ wordDict = ["cat", "cats", "and", "sand", "dog"]
24
+ Output:
25
+ [
26
+ "cats and dog",
27
+ "cat sand dog"
28
+ ]
29
+
30
+ Example 2:
31
+
32
+ Input:
33
+ s = "pineapplepenapple"
34
+ wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
35
+ Output:
36
+ [
37
+ "pine apple pen apple",
38
+ "pineapple pen apple",
39
+ "pine applepen apple"
40
+ ]
41
+ Explanation: Note that you are allowed to reuse a dictionary word.
42
+
43
+ Example 3:
44
+
45
+ Input:
46
+ s = "catsandog"
47
+ wordDict = ["cats", "dog", "sand", "and", "cat"]
48
+ Output:
49
+ []
20
50
*/
51
+
21
52
public class _140 {
53
+ public static class Solution1 {
22
54
public List <String > wordBreak (String s , List <String > wordDict ) {
23
- return dfs (s , wordDict , new HashMap <>());
55
+ return dfs (s , wordDict , new HashMap <>());
24
56
}
25
57
26
58
List <String > dfs (String s , List <String > wordDict , HashMap <String , List <String >> map ) {
27
- if (map .containsKey (s )) {
28
- return map .get (s );
29
- }
59
+ if (map .containsKey (s )) {
60
+ return map .get (s );
61
+ }
30
62
31
- ArrayList <String > result = new ArrayList <>();
32
- if (s .length () == 0 ) {
33
- result .add ("" );
34
- return result ;
35
- }
63
+ ArrayList <String > result = new ArrayList <>();
64
+ if (s .length () == 0 ) {
65
+ result .add ("" );
66
+ return result ;
67
+ }
36
68
37
- for (String word : wordDict ) {
38
- if (s .startsWith (word )) {
39
- List <String > subList = dfs (s .substring (word .length ()), wordDict , map );
40
- for (String sub : subList ) {
41
- result .add (word + (sub .length () == 0 ? "" : " " ) + sub );
42
- }
43
- }
69
+ for (String word : wordDict ) {
70
+ if (s .startsWith (word )) {
71
+ List <String > subList = dfs (s .substring (word .length ()), wordDict , map );
72
+ for (String sub : subList ) {
73
+ result .add (word + (sub .length () == 0 ? "" : " " ) + sub );
74
+ }
44
75
}
45
- map .put (s , result );
46
- return result ;
76
+ }
77
+ map .put (s , result );
78
+ return result ;
47
79
}
48
-
49
- }
80
+ }
81
+ }
0 commit comments