当前位置:网站首页>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];
}
};
边栏推荐
猜你喜欢
5. Software testing ----- automated testing
MySQL-多表查询
[Example构造方法增加notNull参数,默认false,允许值为null,值为null的时候不加入到条件中
openCV第二篇
.NET in-depth analysis of the LINQ framework (four: IQueryable, IQueryProvider interface details)
孩子坐不住就是不专注?猿辅导揭秘专注力的三大误区
Wei Dongshan Digital Photo Frame Project Learning (5) Transplantation of libjpeg-turbo
Fiddler基本使用
initramfs详解-----初识initramfs
qt opengl 使用不同的颜色绘制线框三角形
随机推荐
monkey 压测
二叉树的前序遍历、中序遍历、后序遍历和层序遍历
Topic Modeling of Short Texts: A Pseudo-Document View
[Arduino] Reborn Arduino Monk (3)----Arduino function
Spark SQL简介
JVM内部结构图及各模块运行机制总结
PHICOMM(斐讯)N1盒子 - Armbian5.77(Debian 9)基本配置
如何让优炫数据库开机自启
部门之间,互不信任正常吗?(你是否遇到过)
QCheckBox、margin、border、pandding、QHoxLayout、QSplitter、QSpacerItem
ldap创建公司组织、人员
lombok 下的@Builder和@EqualsAndHashCode(callSuper = true)注解
一些面试的总结
YYGH-BUG-06
The cornerstone of high concurrency: multithreading, daemon threading, thread safety, thread synchronization, mutual exclusion lock, all in one article!...
VS2010 组件列表与对应名称
服务器在线测速系统源码
工作两年成跳槽高峰期,程序员会在一家公司待多久?
征集 |《新程序员》专访“Apache之父”Brian Behlendorf,你最想问什么?
MySQL里获取当前周、月、季的第一天/最后一天