LeetCode[139] Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].Return true because "leetcode" can be segmented as "leet code".
DFS + Memorization
复杂度
O(N^2),O(N)
思路
用map来记录已经判断过的string,每次判断是否开头是在map中的出现的字符串。
代码
Map<String, Boolean> map = new HashMap<>();
public boolean wordBreak(String s, Set<String> wordDict) {
if(s.length() == "") return true;
// use map to 保留已经搜索过的信息;
if(map.containsKey(s)) return map.get(s);
for(String d : wordDict) {
if(s.startsWith(d)) {
if(wordBreak(s.substring(d.length()), wordDict) {
return true;
}
}
}
map.put(s, false);
return false;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。