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"]
.
在代码当中有英文的注释,关键是理解wordBreak的思想,其实是向前探测其数字是否符合要求。然后再用dfs递归,把所有符合结果的路径求解出来。
public class Solution {
// 19:10 -> 20:19 get accept
// first we should mark every outdoor of a character on a string. For example, the out dorr of 'c',the first character in s, is
//'t' and 's',there is no out door at a,because no word in dict is stars with a; and then, use 't' and 's' to find the ourdoors
// of these two characters; At the end, if the last character 'g' is reached, then it is possible to make a sentence by the dict.
// otherwise, no sentence is output.
// To output the sentences, we should use dfs
// 19:10 ->
public ArrayList<String> wordBreak(String s, Set<String> dict) {
//ArrayList<String> res;
boolean isCent = false;
int len = s.length(), lent = 0;
ArrayList<ArrayList<Integer>> dp = new ArrayList<ArrayList<Integer>>();
// I should initialize it at first
for(int i=0;i<len+1;i++){
dp.add(new ArrayList<Integer>());
}
//dp.set(0, new ArrayList<Integer>());
dp.get(0).add(1);
ArrayList<Integer> tmp = dp.get(0);
String word, nw;
for (int k = 0; k <= len; k++) {
tmp = dp.get(k);
if (tmp.size()!=0) {
for (int j = 0; j < tmp.size(); j++) {
//the
int i = tmp.get(j);
for (Iterator<String> it = dict.iterator(); it.hasNext();) {
word = it.next();
lent = word.length();
if (i + lent <= len + 1) {
// index of string is less,but
nw = s.substring(i - 1, i + lent - 1);
if (nw.equals(word)) {
//I should judge whether the index is duplicated
// I must calculate the index of the string and the index of the dp
if(!dp.get(i).contains(i+lent))
{
dp.get(i).add(i + lent);
}
if (i + lent == len + 1) {
isCent = true;
}
}
}
}
}
}
}
if(isCent){
dfs(dp, 1, s, new StringBuffer(), len);
}
return res;
}
ArrayList<String> res = new ArrayList<String>();
void dfs(ArrayList<ArrayList<Integer>> dp, int index,
String s, StringBuffer cent, int len) {
ArrayList<Integer> tmp = null;
tmp = dp.get(index);
if (tmp.size()!=0) {
for (int j = 0; j < tmp.size(); j++) {
String st = s.substring(index - 1, tmp.get(j) - 1);
// I must use another stringbuffer
StringBuffer centTmp = new StringBuffer(cent);
centTmp.append(st);
if (tmp.get(j) != len + 1) {
centTmp.append(" ");
dfs(dp,tmp.get(j), s,centTmp , len);
} else {
res.add(centTmp.toString());
}
}
}
return ;
}
}