Word Break(Medium) 单词分解
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".
解题思路
典型的DP题,dp[i]表示前i个字符是否可分解成单词,那么 dp[i] = dp[j] && dict.contains(s.substring(j, i)) (j = 0, 1, ..., i-1, 只要任意一个满足即可);
public boolean wordBreak(String s, Set<String> dict) {
int len = s.length();
boolean[] dp = new boolean[len + 1];
dp[0] = true;
for(int i = 1; i <= len; i++) {
for(int j = 0; j < i; j++) {
if(dp[j] && dict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[len];
}