给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,确定 s 是否可以被空格分割为一个或多个在字典里出现的单词。你可以假设字典中无重复的单词。

例如,给出

s = "leetcode",

dict = ["leet", "code"]。

返回 true 因为 "leetcode" 可以被切分成 "leet code"。

详见:https://leetcode.com/problems/word-break/description/

Java实现:



class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int n=s.length();
//dp[i]表示前i个字符能不能被dict完美划分
boolean[] dp=new boolean[n+1];
dp[0]=true;
for(int i=1;i<=n;++i){
for(int j=0;j<i;++j){
//substring是前闭后开
String tmp=s.substring(j,i);
if(dp[j]&&wordDict.contains(tmp)){
dp[i]=true;
break;
}
}
}
return dp[n];
}
}