Word Break II
来源:互联网 发布:被网络诈骗怎么报案 编辑:程序博客网 时间:2024/04/30 15:41
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"]
.
public List<String> wordBreak(String s, Set<String> dict) { boolean[] canBreak;Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();List<String> first = new ArrayList<String>();first.add("");map.put(0, first);for (int i = 1; i <= s.length(); i++) {for (int j = 0; j < i; j++) {if (map.get(j) != null) {if (dict.contains(s.substring(j, i))) {List<String> preLists = map.get(j);List<String> newLists = new ArrayList<String>();for (String str: preLists) {newLists.add(str + (str.length() > 0 ? " " : "") + s.substring(j, i));}if (map.get(i) == null) {map.put(i, newLists);} else {map.get(i).addAll(newLists);}}}}}return map.get(s.length()); }递归:
public List<String> wordBreak(String s, Set<String> dict) { List<List<String>> result = new ArrayList<List<String>>(); helper(result, new ArrayList<String>(), s, 0, dict); List<String> res = new ArrayList<String>(); for (List<String> list : result) { String sentence = ""; for (String str : list) { sentence = sentence + str + " "; } sentence = sentence.substring(0, sentence.length()); res.add(sentence); } return res; } void helper(List<List<String>> result, List<String> preResult, String s, int pos, Set<String> dict) { if (pos == s.length()) { result.add(preResult); return; } for (int i = pos + 1; i < s.length(); i++) { if (dict.contains(s.substring(pos, i))) { List<String> newResult = new ArrayList<String>(preResult); preResult.add(s.substring(pos, i)); helper(result, newResult, s, i, dict); } } }
0 0
- Word Break && Word Break II
- Word Break && Word Break II
- [leetcode]Word Break II
- Word Break II
- Word Break II
- LeetCode:Word Break II
- Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- Word Break II
- Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- Word Break II
- Word Break II
- UNIX环境高级编程学习环境搭建---apue.h
- ubuntu利用dd命令备份系统
- c程序的编译过程
- Trie树与后缀树
- [百度笔试] 2014百度校园招聘软件研发题--武汉
- Word Break II
- 16. 事件
- Android基础之——第一个项目Hello word!
- Java学习笔记之反射机制初探
- [腾讯笔试] 2015腾讯校园招聘软件测试笔试题(笔试时间:2014-9-13
- jackson
- 【Android 应用开发】 ActionBar 样式详解 -- 样式 主题 简介 Actionbar 的 icon logo 标题 菜单样式修改
- TCP、UDP、IP报头结构体分析
- 找实习/工作经验心得分享-偏IT技术向