dp|拆分控制

lc472

只尝试 `len < n` 确保由"更短单词"拼成;等长词不会参与

// 思路(排序+逐词断词 DP,长度去重优化)

// - 按长度升序处理,只用"更短"的词去拼当前词。

// - 对每个词做 word-break:`dpi` 表示前 i 位可由更短词拼出;只尝试出现过的"长度集合",剪枝快。

// - 复杂度:总 O(∑L · |lenSet|);因每词长度 ≤ 30、lenSet ≤ 30,且总长度 ≤ 1e5,足够快。

class Solution {

public:

std::vector<std::string> findAllConcatenatedWordsInADict(std::vector<std::string>& w)

{

std::sort(w.begin(), w.end(), \[\](auto& a, auto& b){ return a.size() < b.size(); });

std::unordered_set<std::string> S;

std::unordered_set<int> seenLen;

std::vector<int> L; // 已出现的不同长度

std::vector<std::string> ans;

for (auto& s : w) {

int n = s.size();

if (!S.empty() && ok(s, S, L)) ans.push_back(s);

S.insert(s);

if (seenLen.insert(n).second) L.push_back(n);

}

return ans;

}

private:

static bool ok(const std::string& s, const std::unordered_set<std::string>& S, const std::vector<int>& L)

{

int n = s.size();

std::vector<char> dp(n + 1); dp0 = 1;

for (int i = 0; i < n; ++i) if (dpi) {

for (int len : L) if (len < n && i + len <= n && S.count(s.substr(i, len)))

{

if ((dpi + len = 1) && dpn) return true;

}

}

return dpn;

}

};

lc466

找出由n1个s1拼接成的字符串里,++最多能包含多少个完整的s2(再除以n2得最终结果)++

过程中用循环检测来避免重复计算,提升效率

class Solution

{

//s1*n1删除某些字符能得到s2*n2*m

public:

int getMaxRepetitions(std::string s1, int n1, std::string s2, int n2) {

using ll = long long;

// 不可匹配的快速判零

std::array<int,26> has{}; for(char c: s1) hasc-'a'=1;

for(char c: s2) if(!hasc-'a') return 0;

int L2 = s2.size(), j = 0;

std::vector<int> first(L2, -1);

std::vector<ll> cnt(L2, 0);

ll c2 = 0; // 已匹配完整 s2 的次数

for (ll i = 0; i < n1; ++i) {

for (char c : s1) {

if (c == s2j && ++j == L2) j = 0, ++c2;

}

if (firstj != -1) { // 发现循环

ll i0 = firstj, c20 = cntj;

ll perBlk = i - i0, perCnt = c2 - c20;

ll loops = (n1 - 1 - i) / perBlk;

c2 += loops * perCnt;

i += loops * perBlk;

} else {

firstj = i; cntj = c2;

}

}

return (int)(c2 / n2);

}

};

lc791

直接返回 true / false 确保"在order中的字符优先排前面"

class Solution {

public:

string customSortString(string order, string s)

{

unordered_map<char,int> hash;

for(int i=0;i<order.size();i++)

{

hashorder\[i]=i;

}

sort(s.begin(),s.end(),\&(char& a,char& b)

{

if(hash.count(a) && hash.count(b))

return hasha<hashb;

else if(hash.count(a))

return true;

else if(hash.count(b))

return false;

else

return a<b;

});

return s;

}

};

相关推荐
GIS阵地2 小时前
QgsRasterDataProvider 完整详解(QGIS 3.40.13 C++)
开发语言·c++·qt·开源软件·qgis
charlie1145141914 小时前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
米罗篮6 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
肖爱Kun6 小时前
C++设计策略模式
开发语言·c++·策略模式
炸膛坦客8 小时前
单片机/C/C++八股:(二十四)编译文件( .bin 和 .hex ,包括 .elf 和 .axf )
c语言·c++·单片机
cpp_25019 小时前
P10098 [ROIR 2023] 地铁建设 (Day 2)
数据结构·c++·算法·贪心·二分答案·洛谷题解
hehelm9 小时前
IO 多路复用 — Reactor
linux·服务器·网络·数据库·c++
灵晔君10 小时前
【C++】二叉搜索树
开发语言·c++
鱼子星_11 小时前
【C++】内存管理:内存分布,new/delete的使用及细节处理,new/delete的底层,定位new表达式
开发语言·c++·笔记
鱼子星_11 小时前
【C++】string(上):string的基本使用
c++·笔记·字符串