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搜,从前往后看看有没有在字典里出现过的,有就切,并且递归往下传。
必须要记忆优化,否则太多重复判断直接TLE
HashMap<String, Boolean> hashMap=new HashMap<>(1024);
public boolean wordBreak(String s, Set<String> wordDict)
{
return dfs(s, wordDict);
}
private boolean dfs(String s, Set<String> dict)
{
int len = s.length();
if (len == 0)
return true;
if(hashMap.containsKey(s))
return hashMap.get(s);
for (int i = 1; i <= len; i++)
{
String substr = s.substring(0, i);
if (dict.contains(substr))
if (dfs(s.substring(i), dict))
{
hashMap.put(s, true);
return true;
}
}
hashMap.put(s, false);
return false;
}
-----------------------------------------------------------------------------------------------------------
另外比较好的方法dp,摘自:https://leetcode.com/discuss/18904/java-implementation-using-dp-in-two-ways
f[i] stands for whether subarray(0, i) can be segmented into words from the dictionary. So f[0] means whether subarray(0, 0) (which is an empty string) can be segmented, and of course the answer is yes.
The default value for boolean array is false. Therefore we need to set f[0] to be true.
public boolean wordBreak(String s, Set<String> dict) {
boolean[] f = new boolean[s.length() + 1];
f[0] = true;
for(int i=1; i <= s.length(); i++){
for(int j=0; j < i; j++){
if(f[j] && dict.contains(s.substring(j, i))){
f[i] = true;
break;
}
}
}
return f[s.length()];
}