LeetCode Word Break II
2015-09-13 01:40
232 查看
原题链接在这里:https://leetcode.com/problems/word-break-ii/
题目:
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 =
dict =
A solution is
题解:
本题是Word Break的进阶题,要返回所有wordbreak的结果。
本题参照了这篇帖子:/article/4896867.html
首先更具isWordBreak判断是否能拆,这一步不能省略。若能拆看从头到尾走,找到了一个wordDict里包含的字符串,然后从后一个点就用递归方法调用helper, 递归的stop condition是能走到正好结尾,否则跳出for loop, res不变。
Note: helper的for loop中若wordDict包含当前sb.toString(), 应该建立一个新的string, newString, 它相当于一个copy, 因为回朔到这点时,str应该回到最开始的时候,若不用这个copy当回到这点时str可能已经不是最开始的状态。
AC Java:
题目:
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"].
题解:
本题是Word Break的进阶题,要返回所有wordbreak的结果。
本题参照了这篇帖子:/article/4896867.html
首先更具isWordBreak判断是否能拆,这一步不能省略。若能拆看从头到尾走,找到了一个wordDict里包含的字符串,然后从后一个点就用递归方法调用helper, 递归的stop condition是能走到正好结尾,否则跳出for loop, res不变。
Note: helper的for loop中若wordDict包含当前sb.toString(), 应该建立一个新的string, newString, 它相当于一个copy, 因为回朔到这点时,str应该回到最开始的时候,若不用这个copy当回到这点时str可能已经不是最开始的状态。
AC Java:
public class Solution { public List<String> wordBreak(String s, Set<String> wordDict) { List<String> res = new ArrayList<String>(); if(s == null || s.length() == 0){ return res; } if(isBreak(s,wordDict)){ helper(s,wordDict,0,"",res); } return res; } private void helper(String s, Set<String> wordDict, int start, String item, List<String> res){ if(start == s.length()){ res.add(item); return; } StringBuilder sb = new StringBuilder(); for(int i = start; i<s.length(); i++){ sb.append(s.charAt(i)); if(wordDict.contains(sb.toString())){ String str = ""; //这里必须要做复制 if(item.length() == 0){ str = sb.toString(); }else{ str = item + " " + sb.toString(); } helper(s,wordDict,i+1,str,res); } } } private boolean isBreak(String s, Set<String> wordDict){ if(s == null || s.length() == 0){ return true; } boolean [] res = new boolean[s.length()+1]; res[0] = true; for(int i = 1; i<res.length; i++){ StringBuilder sb = new StringBuilder(s.substring(0,i)); for(int j = 0; j<i; j++){ if(res[j] && wordDict.contains(sb.toString())){ res[i] = true; } sb.deleteCharAt(0); } } return res[res.length-1]; } }
相关文章推荐
- composer更新不成功,启用国内镜像网站的配置更改办法
- JAVA学习基础篇第一周
- Leetcode Perfect Squares
- Spring与ehcache整合,通过Spring原生注解使用缓存
- UVALive 5902 Movie collection(树状数组)
- 服务器环境配置nginx / php / php-fpm(一)
- Android应用进程间通信之Messenger信使使用及源码浅析
- book publisher and study
- Xcode7免证书真机调试
- linux centos 下php的mcrypt扩展
- jQuery part1
- securecrt同时向多个tab窗口发送相同的命令
- poj 3984
- C++ 链表
- get与post方法
- andorid系统使用硬件资源_传感器1
- jni中字符转换中文乱码的处理方法
- 算法基础(三)---- 计算字符串数字平均值
- Effective C++ 条款51 编写new和delete时需固守常规
- 2012年清华大学计算机研究生机试真题