leetcode 140. Word Break II
这一题是去年面试出门问问的一道题,当时给的写法整理如下,超时了。
因为后续的部分重复太多了。
public class Solution {
public static void main(String[] args){
Solution s = new Solution();
String ss = "catsanddog";
List<String> dict = new ArrayList<String>();
dict.add("cat");
dict.add("cats");
dict.add("sand");
dict.add("and");
dict.add("dog");
s.wordBreak(ss, dict);
}
public List<String> wordBreak(String s, List<String> wordDict) {
int max_len = 0;
for(int k=0;k<wordDict.size();k++){
if(wordDict.get(k).length()>max_len)
max_len = wordDict.get(k).length();
}
return backws(s,wordDict,max_len);
}
private List<String> backws(String s, List<String> wordDict, int max_len) {
// TODO Auto-generated method stub
List<String> res = new ArrayList<String>();
for(int i=0;i<s.length();i++){
if(wordDict.contains(s.substring(0, i+1))){
List<String> left = backws(s.substring(i+1), wordDict, max_len);
if(i==s.length()-1){
res.add(s.substring(0, i+1));
}
if(left.size()==0) continue;
for(int k=0;k<left.size();k++){
StringBuilder r = new StringBuilder();
r.append(s.substring(0, i+1));
r.append(" ");
r.append(left.get(k));
res.add(r.toString());
}
}else if(i+1>max_len){
break;
}
}
return res;
}
}
加上 memorize acc:
public class Solution {
public static void main(String[] args){
Solution s = new Solution();
String ss = "catsanddog";
List<String> dict = new ArrayList<String>();
dict.add("cat");
dict.add("cats");
dict.add("sand");
dict.add("and");
dict.add("dog");
s.wordBreak(ss, dict);
}
public List<String> wordBreak(String s, List<String> wordDict) {
int max_len = 0;
for(int k=0;k<wordDict.size();k++){
if(wordDict.get(k).length()>max_len)
max_len = wordDict.get(k).length();
}
return backws(s,wordDict,max_len, new HashMap<String,List<String>>());
}
// dfs
private List<String> backws(String s, List<String> wordDict, int max_len,
HashMap<String, List<String>> map) {
if(map.containsKey(s)) return map.get(s);
List<String> res = new ArrayList<String>();
for(String word: wordDict){
if(s.startsWith(word)){
List<String> left = backws(s.substring(word.length()),wordDict,max_len,map);
if(word.length()==s.length()){
res.add(word);
}
// if(left.size()==0) continue;
for(int k=0;k<left.size();k++){
String r = word + " " + left.get(k);
res.add(r);
/*
StringBuilder r = new StringBuilder();
r.append(word);
r.append(" ");
r.append(left.get(k));
res.add(r.toString());
*/
}
map.put(s, res);
}
}
return res;
}
}