Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
Output:
[
“cats and dog”,
“cat sand dog”
]
给出一个字典,一个字符串s,要求用空格把s分割成字典里的单词,要列出所有可能性
思路:
如果单纯用眼睛看来分割,应该是找到以字典单词开头的单词,去掉该单词后继续找下一个字典单词,一个一个去掉再看剩下的,也就是递归。
如果遇到了相同的后面又重复的子字符串,这时候就不需要重复递归,需要一个记忆功能,key是子字符串,value是所有可能性的list,如果要查找的字符串在key里,返回对应value的list即可
class Solution {
HashMap<String, List<String>> hash = new HashMap<>();
public List<String> wordBreak(String s, List<String> wordDict) {
if(hash.containsKey(s)) {
return hash.get(s);
}
List<String> result = new ArrayList<>();
for(String word : wordDict) {
if(!s.startsWith(word)) {
continue;
}
if(s.length() == word.length()) {
result.add(word);
continue;
}
List<String> tmp = wordBreak(s.substring(word.length()), wordDict);
//开头的单词word要和list中每种可能的字符串结合
for(String str : tmp) {
String solution = "";
solution += word;
solution += " ";
solution += str;
result.add(solution);
}
}
hash.put(s, result);
return result;
}
}