Word Break II
来源:互联网 发布:linux中开启ftp端口号 编辑:程序博客网 时间:2024/06/06 09:20
题目描述:
Given a string s and a dictionary of words dict, add spaces ins 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"]
.
dfs会超时:
public class Solution { public List<String> wordBreak(String s, Set<String> wordDict) {List<String> result=new ArrayList<String>();StringBuilder sb=new StringBuilder();getScentence(s, wordDict, 0, sb, result);return result; }public void getScentence(String s, Set<String> wordDict,int start,StringBuilder sb,List<String> result){if(start==s.length()){int len=sb.length();String str=sb.delete(len-1, len).toString();result.add(str);return;}int len=sb.length();for(int i=start+1;i<=s.length();i++){String substr=s.substring(start, i);if(wordDict.contains(substr)){sb.append(substr).append(" ");getScentence(s, wordDict, i, sb, result);sb.delete(len, len+substr.length()+1);//这里要+1,小心细节- -!}}}}带备忘录的dfs算法:
public class Solution { Map<String, List<String>> mem = new HashMap<>();public List<String> wordBreak(String s, Set<String> wordDict) { if (mem.get(s) != null) return mem.get(s); List<String> result = new ArrayList<>(); if (wordDict.contains(s)) result.add(s); for (int i = 1; i < s.length(); i++) { String word = s.substring(0, i); if (wordDict.contains(word)) { List<String> tmp = wordBreak(s.substring(i), wordDict); for (String str : tmp) { result.add(word + " " + str); } } } mem.put(s, result); return result;}}
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
- web容器 web服务器 servlet/jsp容器 之间的区别和关系
- python+opencv开发环境之不能import cv的问题
- HDU 2829 (斜率优化)
- 我的shiro之旅:自定义filter
- 编码转换工具编写笔记
- Word Break II
- 了解CI
- Git - 基本概念(更改提交)
- Mac下搭建GO环境
- 以rem为单位移动端页面开发
- Android 混淆代码总结
- shell
- Windows内核编程 文件监控(ssdt hook)
- Linux和UNIX下如何配置PWC连SQL Server数据源