【发布时间】:2020-08-08 20:28:21
【问题描述】:
我正在尝试实现“分词”算法。
问题: 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,确定 s 是否可以分割成一个或多个字典单词的空格分隔序列。
注意:
字典中的同一个词可能会在分词中重复使用多次。 您可以假设字典不包含重复的单词。
例子:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
我的解决方案:
var wordBreak = function(s, wordDict) {
if(!wordDict || wordDict.length === 0)
return false;
while(wordDict.length > 0 || s.length > 0) {
const word = wordDict.shift();
const index = s.indexOf(word);
if(index === -1) {
return false;
}
s = s.substring(0, index) + s.substring(index+word.length, s.length);
}
return s.length === 0 && wordDict.length === 0 ? true : false;
};
它适用于上面的示例(输入)。但是,下面的输入失败了。
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.
我怎样才能跟踪我已经删除的单词并在最后检查它。上面这个输入,剩下的 s 字符串包含字典中的“apple”,所以输出应该为真。
谢谢
【问题讨论】:
-
是否允许在字典中有一些词是其他词的一部分,例如 ['part', 'partner']?
-
你真的要使用
shift吗?这会修改您的wordDict,使其无法重复使用。另外,您是在询问输入字符串是否仅包含wordDict中的子字符串,还是要在wordDict中的每个单词实例周围放置空格?换句话说,你对字符串 "leetecode" 有什么期望(在 leet 和 code 之间放置一个 "e")?
标签: javascript dynamic-programming