Word Break II 求把字符串拆分为字典里的单词的所有方案 @LeetCode
来源:互联网 发布:英语网络 编辑:程序博客网 时间:2024/05/18 00:02
这道题类似 Word Break 判断是否能把字符串拆分为字典里的单词 @LeetCode 只不过要求计算的并不仅仅是是否能拆分,而是要求出所有的拆分方案。因此用递归。
但是直接递归做会超时,原因是LeetCode里有几个很长但是无法拆分的情况,所以就先跑一遍Word Break,先判断能否拆分,然后再进行拆分。
递归思路就是,逐一尝试字典里的每一个单词,看看哪一个单词和S的开头部分匹配,如果匹配则递归处理S的除了开头部分,直到S为空,说明可以匹配。
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 class Solution { public List<String> wordBreak(String s, Set<String> dict) { List<String> list = new ArrayList<String>(); List<String> ret = new ArrayList<String>(); rec(s, dict, list, ret); return ret; } public void rec(String s, Set<String> dict, List<String> list, List<String> ret) { if(!isBreak(s, dict)){ // test before run to avoid TLE return; } if(s.length() == 0) { String concat = ""; for(int i=0; i<list.size(); i++) { concat += list.get(i); if(i != list.size()-1) { concat += " "; } } ret.add(concat); return; } for(String cur : dict) { if(cur.length() > s.length()) { // avoid out of boundary continue; } String substr = s.substring(0, cur.length()); if(substr.equals(cur)) { list.add(substr); rec(s.substring(cur.length()), dict, list, ret); list.remove(list.size()-1); } } } public boolean isBreak(String s, Set<String> dict) { boolean[] canBreak = new boolean[s.length()+1]; canBreak[0] = true; for(int i=1; i<=s.length(); i++) { boolean flag = false; for(int j=0; j<i; j++) { if(canBreak[j] && dict.contains(s.substring(j,i))) { flag = true; break; } } canBreak[i] = flag; } return canBreak[s.length()]; }}
0 0
- Word Break II 求把字符串拆分为字典里的单词的所有方案 @LeetCode
- Word Break 判断是否能把字符串拆分为字典里的单词 @LeetCode
- 【LeetCode】Word Break 单词拆分
- 字符串单词拆分 Word Break
- [LeetCode] word break 字符串的划分
- LeetCode 140. Word Break II(单词切分)
- [leetcode]Word Break II
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- [LeetCode] Word Break II
- Word Break II -- LeetCode
- LeetCode (Word Break II )
- 静态方法可以直接用类引用,不用实例化
- LeetCode: Linked List Cycle
- LeetCode: Linked List Cycle II
- C++ STL简介
- C++学习的50条忠告
- Word Break II 求把字符串拆分为字典里的单词的所有方案 @LeetCode
- JCIP_4_01_扩展现有安全类_客户端加锁
- 今日作息及食谱(8.13)
- Changing the Cordova app icon
- 如果是作为客户端的HTTP+JSON接口工程,没有JSP等view视图的情况下,使用Jersery框架开发绝对是第一选择。而在基于Spring3 MVC的架构下,对HTTP+JSON的返回类型也有很好
- Sublime Text 2 Error trying to parse settings
- 使用PhoneGap Build 将web applications打包成native mobile applications
- 编写一个标准strcpy函数
- 如何构建优质代码