题目介绍
力扣139题:leetcode-cn.com/problems/wo…
动态规划
初始化 dp=[False,⋯,False],长度为 n + 1。n 为字符串长度。dp[i] 表示 s 的前 i 位是否可以用 wordDict 中的单词表示。
初始化 dp[0]=True,空字符可以被表示。
遍历字符串的所有子串,遍历开始索引 i,遍历区间 [0,n):
遍历结束索引 j,遍历区间 [i+1,n+1):
若 dp[i]=True 且 s[i,⋯,j) 在 wordlist 中:dp[j]=True。解释:dp[i]=True 说明 s 的前 i 位可以用wordDict 表示,则 s[i,⋯,j) 出现在 wordDict 中,说明 s 的前 j 位可以表示。最终返回 dp[n]的值即可
代码如下:
public class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int length = s.length();
boolean[] dp = new boolean[length + 1];
//设置默认值为false
Arrays.fill(dp, false);
dp[0] = true;
for (int i = 0; i < length; i++) {
if (!dp[i]) {
continue;
}
for (String word : wordDict) {
//startsWith(word, i)表示从索引i开始,是否以字符串word开头
if (word.length() + i <= s.length() && s.startsWith(word, i)) {
dp[i + word.length()] = true;
}
}
}
return dp[length];
}
}
复杂度分析
- 时间复杂度:O(n^2)
- 空间复杂度:O(n)