-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution_140.java
More file actions
81 lines (67 loc) · 2.07 KB
/
Solution_140.java
File metadata and controls
81 lines (67 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
140. 单词拆分 II
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。
返回所有这些可能的句子。
说明:
分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
"cats and dog",
"cat sand dog"
]
示例 2:
输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
解释: 注意你可以重复使用字典中的单词。
示例 3:
输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]
*/
import java.util.*;
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
String s = "catsanddog";
//"catsanddog"
String[] words = new String[]{"cat","cats","and","sand","dog"};
List<String> wordDict = new ArrayList<>(Arrays.asList(words));
System.out.println(solution.wordBreak(s, wordDict));
}
List<String> ans = new ArrayList<>();
public List<String> wordBreak(String s, List<String> wordDict) {
return solve(s, wordDict,0);
}
HashMap<Integer, List<String>> map = new HashMap<>();
public List<String> solve(String s, List<String> wordDict, int start) {
if (map.containsKey(start))
return map.get(start);
List<String> res = new ArrayList<>();
if (start == s.length())
res.add("");
for (int end = start + 1; end <= s.length(); end++) {
if (wordDict.contains(s.substring(start, end))) {
List<String> list = solve(s, wordDict, end);
for (String l : list) {
res.add(s.substring(start, end) + (l.equals("") ? "" : " ") + l);
}
}
}
map.put(start, res);
return res;
}
}