140 Word Break II
给出一个字符串和一个字典,求能用字典里的单词将字符串分割的所有可能。
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
详情:https://leetcode.com/problems/word-break-ii/
Java实现:
使用深度遍历的方法,每次判断字符串是否以字典中的单词为开头,如果是开头,继续判断剩余的字符串;如果最后字符串长度为0,那么就找到了能分割字符串的单词组成。这里用一个hashMap保存中间结果,否则会超时。
class Solution { public List<String> wordBreak(String s, List<String> wordDict) { return helper(s, wordDict, new HashMap<String, LinkedList<String>>()); } List<String> helper(String s,List<String> wordDict,HashMap<String,LinkedList<String>> map){ if(map.containsKey(s)){ return map.get(s); } LinkedList<String> res = new LinkedList<>(); if(s.length() == 0){ res.add(""); return res; } for(String word : wordDict){ if(s.startsWith(word)){ List<String> subList = helper(s.substring(word.length()),wordDict,map); for(String sub : subList){ res.add(word + (sub.isEmpty() ? "":" ")+ sub); } } } map.put(s,res); return res; } }
参考:https://www.cnblogs.com/271934Liao/p/7680586.html