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"
.
题目大意:很浅显,这里不解释了,采用官网上的动态规划的解法,注意可能会出现数组越界,区别c++中的substr(pos,len)和java中的substring(beginIndex,endIndex),参数:beginIndex:开始处的索引(包括),endIndex :结束处的索引(不包括)。代码如下:
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
if(dict.isEmpty()) {
return false;
}
if(s.length()==0)
return true;
int length;
length=s.length();
boolean[] wordB=new boolean[length+1];
wordB[0]=true;
for(int i=1;i<=length;i++)
for(int j=0;j<i;j++)
{
if(wordB[j]&&dict.contains(s.substring(j,i)))
{
wordB[i]=true;
break;
}
}
return wordB[length];
}
}