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”.
思路:用f(i)表示 原字符串中下标从0到i-1 的子串能不能被切分。f(i)=1表示可以切分,f(i)=0 表示不可以切分
规定f(0) =1
那么 如果有存在f(j)=1 并且 wordDict中包含 s.substring(j,i) 说明f(i)是可以切分的。
也即 如果存在 f(j) ==1 && wordDict.contains(s.substring(j, i)) 那么有f(i) =1 ,否则对于所有的j都没有一个能满足这样的条件的话,f(i)=0。
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
int n=s.length();
if(n==0 || wordDict.isEmpty()) return false;
int[] f=new int[n+1];
f[0]=1;
for(int i=1;i<=n;i++)
{
for(int j=i-1;j>=0;j--)
{
if(f[j]==1 && wordDict.contains(s.substring(j, i)))
{
f[i]=1;
break;
}
}
}
if(f[n]==1) return true;
else return false;
}
}