Word Break II
来源:互联网 发布:游戏编程directx9.0 编辑:程序博客网 时间:2024/06/04 19:12
Q:
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"]
.
Solution:
A brute force solution:
public class Solution { public List<String> wordBreak(String s, Set<String> dict) { List<String> list = new ArrayList<String>(); addSpace(s, "", 0, dict, list); return list; } void addSpace(String s, String added, int index, Set<String> dict, List<String> list) { if (index == s.length()) { list.add(added); return; } for (int i = index; i < s.length(); i++) { if (dict.contains(s.substring(index, i+1))) { added = added + s.substring(index, i+1) + " "; addSpace(s, added, i+1, dict, list); } } }}
a solution passed on leetcode:
public class Solution { Map<String, List<String> > map = new HashMap<String, List<String> >(); public List<String> wordBreak(String s, Set<String> dict) { List<String> list = new ArrayList<String>(); if (map.containsKey(s)) return map.get(s); for (int i = 1; i <= s.length(); i++) { String left = s.substring(0, i); String right = s.substring(i, s.length()); if (dict.contains(left)) { List<String> newlist = wordBreak(right, dict); for (String str: newlist) list.add(left + " " + str); if (right.length() == 0) list.add(left); } } map.put(s, list); return list; }}
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
- Linux 分析应用程序依赖工具
- vector的成员函数解析
- javascript------实现multiple属性下拉框
- Testin云测:搜狐新闻客户端5.0能否承载张朝阳“个性化阅读”梦想
- BZOJ 2007 NOI2010 海拔 平面图最小割
- Word Break II
- 在Mac OS X上使用HAXM加速Android Emulator
- Windows SublimeText内使用NDK编译Android so(不用cygwin)
- Clojure语法小结
- eclipse自动排版快捷键、自动引入包
- 第十二周项目1--阅读4
- hdu 3820 Golden Eggs 最小割
- 深入认识Tigase XMPP Server(下)
- java中的String类