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".
import java.util.Set;
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
if(dict.isEmpty()){
return false;
}
if(s.length()==0){
return true;
}
int[] state=new int[s.length()+1];
state[0]=1;
for(int i=1;i<=s.length();i++){
for(int j=0;j<i;j++){
if(state[j]==1&&(dict.contains(s.substring(j,i))==true)){
state[i]=1;
break;
}
}
}
if(state[s.length()]==1){
return true;
}else{
return false;
}
}
}