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;

}

};

相关推荐
博客18002 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴2 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨3 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4567 天前
C++进阶(1)——前景提要
c++
夜悊7 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴7 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0017 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾8 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you8 天前
constexpr函数
c++
凡人叶枫8 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++