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 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了