码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 139. Word Break

时间:2019-04-13 21:58:58      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:kmp   code   font   javascrip   length   list   work   class   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

标签:kmp   code   font   javascrip   length   list   work   class   break   

原文地址:https://www.cnblogs.com/promise123/p/10702834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!