算法第十二周作业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())); } } } } }
相关文章推荐
- 算法第十八周作业01
- 算法第五周作业01
- 算法设计与结构基础作业第十二周
- 算法课第十二周作业 | Combination Sum III
- 算法期末作业01
- 算法第十五周作业01
- 算法作业_21(2017.5.11第十二周)
- 算法第十四周作业01
- 【算法分析与设计】【第十二周】542. 01 Matrix
- 算法第九周作业01
- 算法第八周作业01
- 算法第十七周作业01
- 第二周作业01 -- 素数的算法实现
- 算法第十三周作业01
- 算法设计期末作业01-8.3
- 算法第七周作业01
- 计算机算法设计与分析作业01:分治法求解大数乘法+L型骨牌的棋盘覆盖问题
- 【中国大学mooc—浙江大学数据结构2018春】1.3节求最大子列和问题,算法3的实现(对应作业题目:01-复杂度1 最大子列和问题)
- 算法第十六周作业01
- 算法复习之分治算法_01