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,结果华丽丽的超时了。看论坛上采用动态规划,故采用之。
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
boolean[] flags = new boolean[s.length()+1];
flags[0] =true;
for(int i = 0; i<s.length(); i++){
int j =i;
while(j >= 0){
if(flags[j] == true){
if(wordDict.contains(s.substring(j,i+1))){
flags[i+1] =true;
break;
}
}
j--;
}
}
return flags[s.length()];
}
}
时间复杂度应该是O(N^2), 空间复杂度为O(N)。N为字符串长度。