您的位置:首页 > 其它

算法第十二周作业01

2017-04-20 22:11 246 查看

Description

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.

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"]
.

Solution

DFS深度搜索

将s与dict中的元素逐个判断是否startWith,如果是startWith,则向下搜索,否则停止搜索

当搜索到s为空字符串时,即搜索到叶子了,停止搜索,将该结果加入结果集

Code

import java.util.LinkedList;
import java.util.List;

public class Solution {
// 存储结果集
private List<String> result;
// 采用属性变量,减少函数调用时变量压栈
private String s;
private List<String> wordDict;

public List<String> wordBreak(String s, List<String> wordDict) {
result = new LinkedList<>();
this.s = s;
this.wordDict = wordDict;
split(null, s);
return result;
}

private void split(String append, String s){
if("".equals(s)){
// 如果搜索到叶片,则该路径为所求结果之一
// 判断this.s == s是为了确保s刚好是一个单词的情况,此时append为null
result.add(this.s == s ? s : append);
} else {
// 逐个判断s是否以str开头
for(String str : wordDict){
if(s.startsWith(str)){
// 拼接字符串并向下搜索
String tmp = append == null ? str : append + " " + str;
split(tmp, s.substring(str.length()));
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息