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.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
题意:输出能由dict组成S的所有结果集合。
题目链接:https://oj.leetcode.com/problems/word-break-ii/
解法:使用动态规划的思想,stop从最后一个单词出发, start从stop前一个单词出发,开始向前遍历,找出能首位相连并且正好在dict中的单词,将start->stop的值记录下来,然后再从start=0出发,收集所有可能的结果
public List<String> wordBreak(String s, Set<String> dict) {
// mark记录字符串中所有包含dict中字符的start与stop,其中start的位置是mark的自然序列,stops的位置是list<start>
// 这些单词有个限制条件,必须能首尾相连
List<List<Integer>> mark = new ArrayList<List<Integer>>();
for (int i = 0; i < s.length(); i++) {
mark.add(new ArrayList<Integer>());
}
for (int stop = s.length(); stop > 0; stop--) {
// 判断必须为首尾相连的单词,如果不是则结束本次循环
if (stop < s.length() && mark.get(stop).size() == 0)
continue;
for (int start = stop - 1; start >= 0; start--) {
if (dict.contains(s.substring(start, stop))) {
List<Integer> temp = mark.get(start);
temp.add(stop);
mark.set(start, temp);
}
}
}
ArrayList<String> result = new ArrayList<String>();
collect(mark, s, 0, new StringBuffer(), result);
return result;
}
// 遍历收集所有可能的字符串
public void collect(List<List<Integer>> mark, String str, int start,
StringBuffer hascoll, List<String> result) {
List<Integer> stops = mark.get(start);
for (int stop : stops) {
StringBuffer tempsbuffer = new StringBuffer(hascoll);
tempsbuffer.append((start == 0 ? "" : " ")
+ str.substring(start, stop));
if (stop == str.length()) {
result.add(tempsbuffer.toString());
continue;
}
collect(mark, str, stop, tempsbuffer, result);
}
}