139. 单词拆分
完全背包
import java.util.List;
class Solution {
public boolean wordBreak(String s, List wordDict) {
/**
* dp[j]定义为长度为j的字符串是否可以由字典中的子串组成,即[0, j - 1]区间的子串
*/
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int j = 1; j < s.length() + 1; j++) {
for (int i = 0; i < j; i++) {
/**
* 如果dp[i],即前i - 1个字符串可以由字典组成
* 且[i, j - 1]范围的子串也在字典中,则[0, j - 1]区间满足条件
*/
if (dp[i] && wordDict.contains(s.substring(i, j))){
dp[j] = true;
}
}
}
return dp[s.length()];
}
}
/**
* 时间复杂度 O(n^2)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/word-break/