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/

本文详细介绍了如何将给定字符串s拆分成字典中有效单词组成的句子,并列举了实例。通过实例演示了如何使用算法实现字符串拆分,并返回所有可能的句子组合。
——Leetcode系列(十二)&spm=1001.2101.3001.5002&articleId=35842545&d=1&t=3&u=76d5396cf73d45a38115e4baad90c98f)
1054

被折叠的 条评论
为什么被折叠?



