设为首页 加入收藏

TOP

LeetCode―Word Break
2015-07-20 17:18:28 来源: 作者: 【 】 浏览:3
Tags:LeetCode Word Break

Given a string s and a dictionary of words dict, determine ifs can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

在这个例子当中,主要是为了看一个句子字符串中的词语能不能够都划分为词典中的词语

flag[j]为true,那么就是要求存在一个变量k,能够满足flag[k]为ture,同时substr(k,j-k)是在字典当中的

但是在这个例子当中是不关心最终的划分方式

?

    class Solution {  
    public:  
        bool wordBreak(string s, unordered_set
  
    &dict) {  
            int length = s.size();
	vector
   
     val(length+1,false); val[0] = true; //<根据长度进行设置 int i = 0; int j = 0; for(i = 0; i < length; i++) { if(val[i])//<前一个长度是可以进行分解的 { for(j = 1; (i+j) <= length; j++) { string tmp = s.substr(i,j); if(dict.count(tmp) > 0) { val[i+j] = true; } } } } return val[length]; } }; 
   
  

对应着有第二个例子:

?

Word Break II

?

?

Given a string s and a dictionary of words dict, add spaces ins to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

在这个例子当中,主要是需要将分解的结果放在一个vector的结构体当中

有一种方法是DFS 方法,还没有研究

这里主要还是借鉴了第一个例子当中的方法,先检测是否能够被划分,如果可以被划分,之后再通过遍历进行存储

?

class Solution {
public:
    void breakWord(vector
  
    &res, string &s, unordered_set
   
     &dict, string str, int idx, vector
    
      &dp) { string substr; for (int len = 1; idx + len <= s.length(); ++len) { if (dp[idx + len] && dict.count(s.substr(idx,len)) > 0) { substr = s.substr(idx, len); if (idx + len < s.length()) { breakWord(res, s, dict, str + substr + " ", idx + len, dp); } else { res.push_back(str + substr); return; } } } } vector
     
       wordBreak(string s, unordered_set
      
        &dict) { vector
       
         dp(s.length() + 1, false); dp[0] = true; for (int i = 0; i < s.length(); ++i) { if (dp[i]) { for (int len = 1; i + len <= s.length(); ++len) { if (dict.count(s.substr(i, len)) > 0) { dp[i + len] = true; } } } } vector
        
          res; if (dp[s.length()]) breakWord(res, s, dict, "", 0, dp); return res; } };
        
       
      
     
    
   
  


?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇漫谈二叉搜索树的基本算法(三种思.. 下一篇java中线程安全的集合对象

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·MySQL 基础入门视频 (2025-12-26 23:20:22)
·小白入门:MySQL超详 (2025-12-26 23:20:19)
·关于 MySQL 数据库学 (2025-12-26 23:20:16)
·SOLVED: Ubuntu 24.0 (2025-12-26 22:51:53)
·Linux 常用命令最全 (2025-12-26 22:51:50)