标签:
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"]
.
思路:和LeetCode93:Restore IP Adress一样,DFS
public class Solution { public List<String> wordBreak(String s, Set<String> wordDict) { List<String> ans=new ArrayList<String>(); if(s==null||wordDict.isEmpty()||!canBreak(s, wordDict)) return ans; dfs(ans,wordDict,s,0,""); return ans; } private void dfs(List<String> ans,Set<String> wordDict,String s, int start, String string) { // TODO Auto-generated method stub if(start>=s.length()){ ans.add(string); return ; } /* if(end==true){ String sub=s.substring(start); if(wordDict.contains(sub)) ans.add(string+" "+sub); return; }*/ for(int i=1;start+i<=s.length();i++){ /*if((start+i)==s.length()) end=true;*/ String sub=s.substring(start,start+i); if(wordDict.contains(sub)){ if(start==0){ dfs(ans,wordDict, s, start+i,sub); }else{ dfs(ans, wordDict,s, start+i, string+" "+sub); } } } } public boolean canBreak(String s, Set<String> wordDict) { int m=s.length(); boolean isSegmented[]=new boolean[m+1]; isSegmented[0]=true; int start=0; for(int i=0;i<m;i++) for(int j=0;j<=i;j++){ isSegmented[i+1]=isSegmented[j]&&wordDict.contains(s.substring(j,i+1)); if(isSegmented[i+1]) break; } return isSegmented[m]; } }
标签:
原文地址:http://www.cnblogs.com/gonewithgt/p/4559667.html