import java.util.*;
public class Solution {
//运用动态规划的思想,用map把已经求得的结果存起来
public ArrayList<String> wordBreak(String s, Set<String> dict) {
ArrayList<String>list=new ArrayList<String>();
if(s==null||s.length()==0||dict==null||dict.size()==0)
return list;
return DFS(s,dict,new LinkedHashMap<String,ArrayList<String>>());
}
//广度遍历
private ArrayList<String>DFS(String s,Set<String>dic,LinkedHashMap<String,ArrayList<String>>map){
if(map.containsKey(s))
return map.get(s);
ArrayList<String>res=new ArrayList<String>();
if(s.length()==0){
res.add("");
return res;
}
for(String subStr:dic){
if(s.startsWith(subStr)){
for(String str:DFS(s.substring(subStr.length()),dic,map)){
res.add(subStr+(str==""?"":" ")+str);
}
}
}
map.put(s,res);
return res;
}
public static void main(String[]args){
System.out.println("Hello World!");
}
}
单词的划分
最新推荐文章于 2023-12-31 21:25:15 发布