Given a string s and a dictionary of words dict, determine ifs 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"
.
题意:给定一个字符串s,和字典,判断s能否由字典内的一个或者多个单词组合而成。
分类:动态规划
解法1:动态规划。使用flag[i]来表示从0到i构成的子串能否用字典来表示,那么我们要求的就是flag[s.length()]
对于flag[i],它由flag[j]和s.substring(j,i)这个子串决定,如果i之前存在一个j,使flag[j]为true,那么我们只要判断j到i这部分子串,是否在字典里面
如果在,那么显然flag[i]也为true
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
if(s.length()==0) return true;
if(wordDict.isEmpty()) return false;
boolean flag[] = new boolean[s.length()+1];
flag[0] = true;
for(int i=1;i<=s.length();i++){
for(int j=i-1;j>=0;j--){
if(flag[j]&&wordDict.contains(s.substring(j,i))){//判断子串
flag[i] = true;
break;
}
}
}
return flag[s.length()];
}
}