
此问题的描述是:
给定一个字符串 s 和一个字符串字典 worddict,如果 s 可以分割成一个或多个字典单词的空格分隔序列,则返回 true。 注意词典中的同一个单词可能会在分词中重复使用多次。
例如:
input: s = "leetcode", worddict = ["leet", "code"] output: true explanation: return true because "leetcode" can be segmented as "leet code".
或者:
input: s = "applepenapple", worddict = ["apple", "pen"] output: true explanation: return true because "applepenapple" can be segmented as "apple pen apple". note that you are allowed to reuse a dictionary word.
或者:
input: s = "catsandog", worddict = ["cats", "dog", "sand", "and", "cat"] output: false
此外,我们的约束表明worddict 的所有字符串都是**唯一**,并且:
继续动态编程解决方案,我们可以看看一种流行的自下而上的方法,我们构建一个 dp 数组来跟踪是否可以在每个索引处将 s 分解为 worddict 中的单词。
每个索引css"> 我 dp 数组中将指示是否可以将整个字符串分解为从索引开始的单词 我 .
| note |
|---|
| dp needs to be of size s.length 1 to hold the edge case of an empty string, in other words, when we're out of bounds. |
让我们用最初的错误值来创建它:
let dp = array.from({ length: s.length + 1 }, () => false); // +1 for the base case, out of bounds
最后一个索引是空字符串,可以认为它是可破坏的,或者换句话说,有效的:
dp[s.length] = true; // base case
向后看,对于 s 的每个索引,我们可以检查从该索引开始是否可以到达 worddict 中的任何单词:
for (let i = s.length - 1; i >= 0; i--) {
for (const word of worddict) {
/* ... */
}
}
如果我们仍在 s (i word.length <= s.length) 的范围内并且找到了单词 (s.slice(i, i word.length) === word),我们'将该槽标记为我们可以打破字符串的“下一个位置”的真值,这将是 i word.length:
for (let i = s.length - 1; i >= 0; i--) {
for (const word of worddict) {
if (i + word.length <= s.length && s.slice(i, i + word.length) === word) {
dp[i] = dp[i + word.length];
}
/* ... */
}
}
如果我们可以将其分解为worddict中的任何单词,我们就不必继续查看其他单词,因此我们可以跳出循环:
for (let i = s.length - 1; i >= 0; i--) {
for (const word of worddict) {
if (i + word.length <= s.length && s.slice(i, i + word.length) === word) {
dp[i] = dp[i + word.length];
}
if (dp[i]) {
break;
}
}
}
最后,我们返回 dp[0] - 如果整个字符串可以分解为 worddict 中的单词,则其值将存储 true,否则为 false:
function wordbreak(s: string, worddict: string[]): boolean {
/* ... */
return dp[0];
}
而且,这是最终的解决方案:
function wordBreak(s: string, wordDict: string[]): boolean {
let dp = Array.from({ length: s.length + 1 }, () => false); // +1 for the base case, out of bounds
dp[s.length] = true; // base case
for (let i = s.length - 1; i >= 0; i--) {
for (const word of wordDict) {
if (i + word.length <= s.length && s.slice(i, i + word.length) === word) {
dp[i] = dp[i + word.length];
}
if (dp[i]) {
break;
}
}
}
return dp[0];
}
时间复杂度为 o(n*m*t) 在哪里 n 是字符串 s, 米 是 worddict 中的单词数,并且 t 是 worddict 中的最大长度单词 - 因为我们有一个嵌套循环,通过切片操作遍历 worddict 中的每个单词,该切片操作使用 s 中每个字符的 word.length。
空间复杂度为 o(n) 因为我们为 s 的每个索引存储 dp 数组。
该系列中的最后一个动态规划问题将是最长递增子序列。在那之前,祝您编码愉快。
以上就是LeetCode 冥想:断词的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号