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"]
.
My Answer:
public class Solution {
private Map<String, Set<String>> map = new HashMap<String, Set<String>>();
public List<String> wordBreak(String s, Set<String> dict) {
Set<String> sentences = toSentence(s, dict);
return setToList(sentences);
}
private Set<String> toSentence(String s, Set<String> dict){
if(! map.containsKey(s)){
Set<String> temp = new HashSet<String>();
map.put(s,temp);
}else{
return map.get(s);
}
int length = s.length();
Set<String> mySet = map.get(s);
if(dict.contains(s)){
mySet.add(s);
}
for(int i = 1; i < length; i++){
String head = s.substring(0,i);
if(!dict.contains(head)){
continue;
}
Set<String> tail = null;
if(! map.containsKey(s.substring(i))){
tail = toSentence(s.substring(i),dict);
}else{
tail = map.get(s.substring(i));
}
if(tail.size() == 0){
continue;
}
Iterator<String> tailIte = tail.iterator();
while(tailIte.hasNext()){
mySet.add(head + " " + tailIte.next());
}
}
return mySet;
}
private List<String> setToList(Set<String> set){
List<String> list = new ArrayList<String>();
Iterator<String> ite = set.iterator();
while(ite.hasNext()){
list.add(ite.next());
}
return list;
}
}
题目来源:https://oj.leetcode.com/problems/word-break-ii/