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"
.
分析:动态规划;
设置一个boolean数组,其中每个元素用来代表字符串s的前i个字符串,是不是能够用set中的字符串表示。
时间复杂度:O(N*N)
空间复杂度:O(N)
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;i++){
for(int j=0;j<=i;j++){
String temp=s.substring(j,i);
if(flag[j]&&wordDict.contains(temp)){
flag[i]=true;
}
}
}
return flag[n];
}
}