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"]
.
https://oj.leetcode.com/problems/word-break-ii/
思路:DFS枚举。
dfs超时
public class Solution { public ArrayList<String> wordBreak(String s, Set<String> dict) { ArrayList<String> res = new ArrayList<String>(); if(s==null || s.length()==0) return res; helper(s,dict,0,"",res); return res; } private void helper(String s, Set<String> dict, int start, String item, ArrayList<String> res) { if(start>=s.length()) { res.add(item); return; } StringBuilder str = new StringBuilder(); for(int i=start;i<s.length();i++) { str.append(s.charAt(i)); if(dict.contains(str.toString())) { String newItem = item.length()>0?(item+" "+str.toString()):str.toString(); helper(s,dict,i+1,newItem,res); } } } }
第二遍记录: dfs写法,依然超时。
public class Solution { public ArrayList<String> wordBreak(String s, Set<String> dict) { ArrayList<String> res = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); wordBreakHelper(res, s, dict, sb); return res; } private void wordBreakHelper(ArrayList<String> res, String s, Set<String> dict, StringBuilder sb) { if ("".equals(s)) { res.add(sb.toString().substring(0, sb.length() - 1)); return; } for (int i = 1; i <= s.length(); i++) { String left = s.substring(0, i); if (dict.contains(left)) { sb.append(left + " "); wordBreakHelper(res, s.substring(i), dict, sb); sb.delete(sb.length() - left.length() - 1, sb.length()); } } } public static void main(String[] args) { String s = "catsanddog"; String[] a = { "cat", "cats", "and", "sand", "dog" }; Set<String> dict = new HashSet<String>(); for (String each : a) dict.add(each); System.out.println(new Solution().wordBreak(s, dict)); } }