当前位置:网站首页>leetcode:139. 单词拆分
leetcode:139. 单词拆分
2022-08-03 02:04:00 【OceanStar的学习笔记】
题目来源
题目描述


题目解析
暴力超时
思路

递归树:
class Solution {
bool process(string &s, int start, std::set<std::string> &dict){
int N = s.size();
if(start == N){
return true;
}
for (int end = start; end < N; ++end) {
std::string prefix = s.substr(start, end - start + 1);
if(dict.count(prefix) && process(s, end + 1, dict)){
return true;
}
}
return false;
}
public:
bool wordBreak(string s, vector<string>& wordDict) {
std::set<std::string> dict;
for(auto &w : wordDict){
dict.insert(w);
}
return process(s, 0, dict);
}
};
加备忘录过。
动态规划
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
std::set<std::string> dict;
for(auto &w : wordDict){
dict.insert(w);
}
int N = s.size();
std::vector<bool> dp(N + 1, false);
dp[N] = true;
for (int start = N - 1; start >= 0; --start) {
for (int end = start; end < N; ++end) {
std::string prefix = s.substr(start, end - start + 1);
if(dict.count(prefix) && dp[end + 1]){
dp[start] = true;
break;
}
}
}
return dp[0];
}
};
前缀树优化
class Solution {
struct Node{
bool end;
std::vector<Node *> nexts;
Node(){
end = false;
nexts.resize(26);
}
};
public:
bool wordBreak(string s, vector<string>& wordDict) {
Node *root = new Node();
for(auto &w : wordDict){
Node *node = root;
int idx = 0;
for (char i : w) {
idx = i - 'a';
if(node->nexts[idx] == nullptr){
node->nexts[idx] = new Node();
}
node = node->nexts[idx];
}
node->end = true;
}
int N = s.size();
std::vector<bool> dp(N + 1, false);
dp[N] = true;
for (int start = N - 1; start >= 0; --start) {
Node *curr = root;
for (int end = start; end < N; ++end) {
char ch = s[end];
curr = curr->nexts[ch - 'a'];
if(curr == nullptr){
break;
}
if(curr->end && dp[end + 1]){
// i...end 真的是一个有效的前缀串 end+1.... 能不能被分解
dp[start] = true;
break;
}
}
}
return dp[0];
}
};
边栏推荐
猜你喜欢

Incorrect datetime value: '2022-01-01' for function str_to_date

DJI内推码(2022年8月2日更新)

实现统一账号登录,sonarqube集成ldap

国标GB28181协议EasyGBS平台项目现场通知消息过多导致系统卡顿该如何解决?

EasyGBS播放器优化:设备通道视频播放出现跳屏问题的修复

超级复杂可贴图布局的初级智能文本提示器

visual studio 2012 为啥这么优秀

数据中台建设(八):数据服务体系建设

The cornerstone of high concurrency: multithreading, daemon threading, thread safety, thread synchronization, mutual exclusion lock, all in one article!...

QT添加资源文件、样式表、qss文件使用
随机推荐
韦东山 数码相框 项目学习(五)libjpeg-turbo的移植
什么情况下DigiCert证书会引起发生安全警报?
常用工具链和虚拟环境-WSL
征集 |《新程序员》专访“Apache之父”Brian Behlendorf,你最想问什么?
Summary of some interviews
QT添加资源文件、样式表、qss文件使用
Incorrect datetime value: '2022-01-01' for function str_to_date
QCheckBox、margin、border、pandding、QHoxLayout、QSplitter、QSpacerItem
禁用token及无感知更新token功能实现
【Swoole系列3.3】单进程管理Process
梅科尔工作室-14天华为培训三
工作两年成跳槽高峰期,程序员会在一家公司待多久?
国标GB28181协议EasyGBS平台项目现场通知消息过多导致系统卡顿该如何解决?
Linux定时任务脚本执行时mysqldump备份异常的问题
.NET in-depth analysis of the LINQ framework (four: IQueryable, IQueryProvider interface details)
常用工具链和虚拟环境-msys2与mingw
【Flink】如何生成 Flink 作业的交互式火焰图?
【Flink】使用arthas在线诊断flink的那些事
简单的布局的初级智能文本提示器
五大靠谱的婚恋相亲APP详细特点缺点分析!