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"
.
思路:对于位置i它我们把i拆成2部分,如果0..j在字典中,并且j+1...i在字典中,那么flag[i]=true,最后只需要判断flag[s.length-1]是不是true即可
代码如下(已通过leetcode)
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
int n=s.length();
boolean[] flag=new boolean[n+1];
flag[0]=true;
for(int i=1;i<n+1;i++) {
for(int j=i-1;j>=0;j--) {
if(flag[j]&&wordDict.contains(s.substring(j,i))) {
flag[i]=true;
break;
}
}
}
return flag[n];
}
}