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”.
解题思路:使用动态规划算法。首先找到前面能够直接作为单词的子串并将它赋值为true。
public boolean wordBreak(String s, Set<String> dict) {
boolean word[]=new boolean[s.length()];//保存前面i长度的字符串能否划分的值
int i;
for(i=0;i<s.length();i++)
if(dict.contains(s.substring(0, i+1)))word[i]=true;
else word[i]=false;
for(i=0;i<s.length();i++){
for(int j=0;j<=i;j++){
if(word[j]&&dict.contains(s.substring(j+1,i+1)))
{//如果前j个字符能够进行划分而且j到i的子串是一个单词则说明前j个字符能够划分
word[i]=true;
break;
}
}
}
return word[s.length()-1];
}