给出一个字符串,和一个字符串集合,问该字符串是否可以有集合中的字符串组成
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"]
.
因为这个例子超时了
Last executed input: | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"] |
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution {
static List<String> ans;
static char[] ch;
static Set<String> set;
public List<String> wordBreak(String s, Set<String> dict) {
ans = new ArrayList<String>();
ch = s.toCharArray();
set = dict;
boolean flag = false;
for(int i = ch.length - 1; i >= 0; --i){
String temp = new String(ch, i, ch.length - i);
if(set.contains(temp)){
flag = true;
break;
}
}
if(flag)
for(int i = 0; i < ch.length; ++i){
String tmp = new String(ch, 0, i + 1);
if(set.contains(tmp))dfs(i + 1, tmp);
}
return ans;
}
public static void dfs(int pre, String s){
if(pre == ch.length){
ans.add(s);
}else if(pre < ch.length){
for(int i = pre; i < ch.length; ++i){
String temp = new String(ch, pre, i - pre + 1);
if(set.contains(temp)){
dfs(i + 1, s + " " + temp);
}
}
}
}
public static void main(String[] args) {
String string = "catsanddog";
HashSet<String> set = new HashSet<>();
for (String str : new String[]{"cat", "cats", "and", "sand", "dog"}) {
set.add(str);
}
Solution s = new Solution();
System.out.println(s.wordBreak(string, set));
}
}