Word Break

Given a string s and a dictionary of words dict, determine if s 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".

利用动态规划算法,创建一个vector记录0-i的字符串是否可以由字典中的词组成,若可以则继续判断剩下的是否可以由字典词组成。为防止s的一部分可以分割而另一部分不可分割,需全部遍历一遍s,而不能根据i跳跃遍历。

复制代码
 1 class Solution {
 2 public:
 3     bool wordBreak(string s, unordered_set<string>& wordDict) {
 4         int n=s.length();
 5         if(n<1) return true;
 6         if(wordDict.empty()) return false;
 7         vector<bool> dp(n+1,false);
 8         dp[0]=true;
 9         for(int i=0;i<n;i++)
10         {
11             if(dp[i])
12             {
13                 for(int j=i;j<n;j++)
14                 {
15                     string tmps=s.substr(i,j-i+1);
16                     if(wordDict.count(tmps))
17                         dp[j+1]=true;
18                 }
19             }
20         }
21         return dp[n];
22     }
23 };
复制代码

 

posted @   鸭子船长  阅读(160)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示