Leetcode 139. Word Break
Posted promise123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 139. Word Break相关的知识,希望对你有一定的参考价值。
Given a non-empty string s and a dictionary wordDict containing a list of non-emptywords, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode"
can be segmented as "leet code"
.
Example 2:
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.
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
一开始以为用kmp算法模板改改就能过,后来才发现我理解错了题意。题目关键是workDict里面几个单词按原本在字典里的前后顺序可以组合成string s。而且注意note提示:
1.workDict里面的单词可以在其他单词字段里出现
2.workDict里面的单词可以重复使用
利用前缀的思想,用dp[i]记录string s[0,i)是否可以成功拆分。
/** * @param {string} s * @param {string[]} wordDict * @return {boolean} */ var wordBreak = function(s, wordDict) { var dp = []; dp[0] = true; for(var i = 1; i <= s.length; i++) { for(var j = 0; j < i; j++) { if(dp[j] === true && wordDict.indexOf(s.substring(j, i)) !== -1) { dp[i] = true; break; } } if(dp[i] !== true) dp[i] = false; } return dp[s.length]; };
以上是关于Leetcode 139. Word Break的主要内容,如果未能解决你的问题,请参考以下文章