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”.
题意:给定字符串及字典,判断该字符串能否被分为多个字典词
思路:用一个长度为字符串长度的数组存储0,l的字符串是否满足题目要求,循环判断该子串是否包含字典词就可以了。
代码:
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
boolean[] state = new boolean[s.length() + 1];
Arrays.fill(state, false);
state[0] = true;
for(int i = 1; i <= s.length(); i++){
for(int j = 0; j < i; j++){
if(state[j] && wordDict.contains(s.substring(j, i))){
state[i] = true;
break;
}
}
}
return state[s.length()];
}
}