
此问题的描述是:
给定一个字符串 s 和一个字符串字典 worddict,如果 s 可以分割成一个或多个字典单词的空格分隔序列,则返回 true。注意词典中的同一个单词可能会在分词中重复使用多次。
例如:
input: s = "leetcode", worddict = ["leet", "code"]output: trueexplanation: return true because "leetcode" can be segmented as "leet code".
或者:
input: s = "applepenapple", worddict = ["apple", "pen"]output: trueexplanation: 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 的所有字符串都是**唯一**,并且:
1 <= s.length <= 3001 <= worddict.length <= 10001 <= worddict[i].length <= 20s 和 worddict[i] 仅由小写英文字母组成。
继续动态编程解决方案,我们可以看看一种流行的自下而上的方法,我们构建一个 dp 数组来跟踪是否可以在每个索引处将 s 分解为 worddict 中的单词。
每个索引 我我我 dp 数组中将指示是否可以将整个字符串分解为从索引开始的单词 我我我.
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
最后一个索引是空字符串,可以认为它是可破坏的,或者换句话说,有效的:
腾讯云AI代码助手
基于混元代码大模型的AI辅助编码工具
172 查看详情
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)o(n * m * t) o(n*m*t) 在哪里 nn n 是字符串 s, 米米米 是 worddict 中的单词数,并且 tt t 是 worddict 中的最大长度单词 – 因为我们有一个嵌套循环,通过切片操作遍历 worddict 中的每个单词,该切片操作使用 s 中每个字符的 word.length。
空间复杂度为 o(n)o(n) o(n) 因为我们为 s 的每个索引存储 dp 数组。
该系列中的最后一个动态规划问题将是最长递增子序列。在那之前,祝您编码愉快。
以上就是LeetCode 冥想:断词的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/784252.html
微信扫一扫
支付宝扫一扫