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,时间复杂度O(2^n),超时。
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
return dfs(0,s,dict);
}
public boolean dfs(int start,String s, Set<String> dict){
if(start==s.length()){
return true;
}
boolean res=false;
for(int i=start;i<s.length();i++){
if(dict.contains( s.substring(start,i+1) )){
res|=dfs(i+1,s,dict);
if(res) break;
}
}
return res;
}
}
dp
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
return dp(s,dict);
}
public boolean dp(String s, Set<String> dict){
if(s==null || s.length()==0) return true;
int n=s.length();
boolean []f=new boolean[n+1];
f[0]=true;
for(int i=1;i<=n;i++){
for(int j=i-1;j>=0;j--){
if( f[j] && dict.contains( s.substring(j,i) )){
f[i]=true;
break;
}
}
}
return f[n];
}
}