当前位置: 首页 > ds >正文

【字典树 滑动窗口】P12318 [蓝桥杯 2024 国研究生组] 分割字符串|普及+

本文涉及的基础知识点

C++算法:滑动窗口及双指针总结
C++前缀树(字典树)

P12318 [蓝桥杯 2024 国研究生组] 分割字符串

题目描述

给定一个仅含小写字母的字符串 S S S ,你可将其分割成任意份子串。我们要求分割后任何一段的长度都不大于 5 5 5 ,且相邻的两个子串不能含有相同的字母。例如 a b c d a e \tt{abcdae} abcdae 分割为 a b c d \tt{abcd} abcd a e \tt{ae} ae 都含 a \tt{a} a,不合法,但可以分割为 a b c d a \tt{abcda} abcda e \tt{e} e,或者 a b \tt{ab} ab c d \tt{cd} cd a e \tt{ae} ae 等。

问该字符串的所有长度小于等于 5 5 5 的本质不同的子串中,哪些在任何分割方案中都没有出现过,按字典序将它们全部输出。

输入格式

输入一行包含一个字符串表示 S S S

输出格式

输出的第一行包含一个整数 t t t ,表示题目要求的字符串的数量。

接下来 t t t 行,每行包含一个要求的字符串 r i r_i ri ,按字典序排序。

输入输出样例 #1

输入 #1

abab

输出 #1

4
ab
aba
ba
bab

说明/提示

评测用例规模与约定

  • 对于 30 % 30\% 30% 的评测用例, ∣ S ∣ ≤ 10 |S| \leq 10 S10
  • 对于 60 % 60\% 60% 的评测用例, ∣ S ∣ ≤ 5000 |S| \leq 5000 S5000
  • 对于所有评测用例, 1 ≤ ∣ S ∣ ≤ 10 5 1 \leq |S| \leq 10^5 1S105

字典树 滑动窗口

性质一:两个相同的相邻字符必须同一组。
结论一:6个或更多相同的连续字符,无法分组,即整个字符串无法划分。其它情况都可以划分,相同字符一组。
判断s[i+5)是否能够划分,has[j] 表示s[i + 5)中是否包括字符’a’+j。用字典树或哈希集合出重。
枚举出现的子串,时间复杂度O(n),如果用字典树,常数大约20; 如果用哈希集合,常数大约160。
判断S[i…i+len-1]能否划分时,左右组都只有一个相同的值。

思路

a[i] =x记录S[i-x+1…i]都相等的最大x。如果max(a)>5,则无法划分,所有长度 ≤ 5 \le5 5的子串都是答案。两层循环,第一层len=1 to 5 第二层循环枚举i=0,i+len <= N,i++
cnt[j]记录S[i…i+len-1]中’a’+j的数量。
注意:某个字符在某处可以划分,某处可以划分,从答案删除。如果aaba。“a”是合法。

代码

核心代码

#include <iostream>
#include <sstream>
#include <vector>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<string>
#include<algorithm>
#include<functional>
#include<queue>
#include <stack>
#include<iomanip>
#include<numeric>
#include <math.h>
#include <climits>
#include<assert.h>
#include<cstring>
#include<list>
#include<array>#include <bitset>
using namespace std;template<class T1, class T2>
std::istream& operator >> (std::istream& in, pair<T1, T2>& pr) {in >> pr.first >> pr.second;return in;
}template<class T1, class T2, class T3 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3>& t) {in >> get<0>(t) >> get<1>(t) >> get<2>(t);return in;
}template<class T1, class T2, class T3, class T4 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4>& t) {in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t);return in;
}template<class T1, class T2, class T3, class T4, class T5, class T6, class T7 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4,T5,T6,T7>& t) {in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t) >> get<4>(t) >> get<5>(t) >> get<6>(t);return in;
}template<class T = int>
vector<T> Read() {int n;cin >> n;vector<T> ret(n);for (int i = 0; i < n; i++) {cin >> ret[i];}return ret;
}
template<class T = int>
vector<T> ReadNotNum() {vector<T> ret;T tmp;while (cin >> tmp) {ret.emplace_back(tmp);if ('\n' == cin.get()) { break; }}return ret;
}template<class T = int>
vector<T> Read(int n) {vector<T> ret(n);for (int i = 0; i < n; i++) {cin >> ret[i];}return ret;
}template<int N = 1'000'000>
class COutBuff
{
public:COutBuff() {m_p = puffer;}template<class T>void write(T x) {int num[28], sp = 0;if (x < 0)*m_p++ = '-', x = -x;if (!x)*m_p++ = 48;while (x)num[++sp] = x % 10, x /= 10;while (sp)*m_p++ = num[sp--] + 48;AuotToFile();}void writestr(const char* sz) {strcpy(m_p, sz);m_p += strlen(sz);AuotToFile();}inline void write(char ch){*m_p++ = ch;AuotToFile();}inline void ToFile() {fwrite(puffer, 1, m_p - puffer, stdout);m_p = puffer;}~COutBuff() {ToFile();}
private:inline void AuotToFile() {if (m_p - puffer > N - 100) {ToFile();}}char  puffer[N], * m_p;
};template<int N = 1'000'000>
class CInBuff
{
public:inline CInBuff() {}inline CInBuff<N>& operator>>(char& ch) {FileToBuf();while (('\r' == *S) || ('\n' == *S) || (' ' == *S)) { S++; }//忽略空格和回车ch = *S++;return *this;}inline CInBuff<N>& operator>>(int& val) {FileToBuf();int x(0), f(0);while (!isdigit(*S))f |= (*S++ == '-');while (isdigit(*S))x = (x << 1) + (x << 3) + (*S++ ^ 48);val = f ? -x : x; S++;//忽略空格换行		return *this;}inline CInBuff& operator>>(long long& val) {FileToBuf();long long x(0); int f(0);while (!isdigit(*S))f |= (*S++ == '-');while (isdigit(*S))x = (x << 1) + (x << 3) + (*S++ ^ 48);val = f ? -x : x; S++;//忽略空格换行return *this;}template<class T1, class T2>inline CInBuff& operator>>(pair<T1, T2>& val) {*this >> val.first >> val.second;return *this;}template<class T1, class T2, class T3>inline CInBuff& operator>>(tuple<T1, T2, T3>& val) {*this >> get<0>(val) >> get<1>(val) >> get<2>(val);return *this;}template<class T1, class T2, class T3, class T4>inline CInBuff& operator>>(tuple<T1, T2, T3, T4>& val) {*this >> get<0>(val) >> get<1>(val) >> get<2>(val) >> get<3>(val);return *this;}template<class T = int>inline CInBuff& operator>>(vector<T>& val) {int n;*this >> n;val.resize(n);for (int i = 0; i < n; i++) {*this >> val[i];}return *this;}template<class T = int>vector<T> Read(int n) {vector<T> ret(n);for (int i = 0; i < n; i++) {*this >> ret[i];}return ret;}template<class T = int>vector<T> Read() {vector<T> ret;*this >> ret;return ret;}
private:inline void FileToBuf() {const int canRead = m_iWritePos - (S - buffer);if (canRead >= 100) { return; }if (m_bFinish) { return; }for (int i = 0; i < canRead; i++){buffer[i] = S[i];//memcpy出错			}m_iWritePos = canRead;buffer[m_iWritePos] = 0;S = buffer;int readCnt = fread(buffer + m_iWritePos, 1, N - m_iWritePos, stdin);if (readCnt <= 0) { m_bFinish = true; return; }m_iWritePos += readCnt;buffer[m_iWritePos] = 0;S = buffer;}int m_iWritePos = 0; bool m_bFinish = false;char buffer[N + 10], * S = buffer;
};class Solution {public:vector<string> Ans(string& str) {const int N = str.length();vector<int> a(N,1);for (int i = 1; i < N; i++) {if (str[i] == str[i - 1]) { a[i] = a[i - 1] + 1; }}const int iMax = *max_element(a.begin(), a.end());const bool bErr = iMax > 5;map<string,int> mErr;		for (int len = 1; len <= 5; len++) {int cnt[26] = { 0 };for (int i = 0; i < len - 1; i++) {cnt[str[i] - 'a']++;}for (int i = 0; i + len <= N; i++) {if (i) {cnt[str[i - 1] - 'a']--;}cnt[str[i + len - 1] - 'a']++;bool curErr =( i && (cnt[str[i - 1] - 'a']));if ((i + len < N)&&(cnt[str[i+len]-'a'])) {curErr = true;}if (curErr || bErr) {mErr[str.substr(i, len)]++;}else {mErr[str.substr(i, len)] = -10 * N;}}}	vector<string> ans;for (const auto& [s, cnt] : mErr) {if (cnt <= 0) { continue; }ans.emplace_back(s);}return ans;}};int main() {
#ifdef _DEBUGfreopen("a.in", "r", stdin);
#endif // DEBUG	ios::sync_with_stdio(0); cin.tie(nullptr);//CInBuff<> in; COutBuff<10'000'000> ob;	string str;cin >> str;
#ifdef _DEBUG	//printf("iH=%d,iA=%d,H=%d,dA=%d",iH,iA,H,dA);//Out(A, ",A=");//Out(B, ",B=");//Out(edge, ",edge=");		/*Out(que, ",que=");*///Out(ab, ",ab=");//Out(par, "par=");//Out(que, "que=");//Out(B, "B=");
#endif // DEBUG	auto res = Solution().Ans(str);	cout << res.size() << "\n";for (const auto& s : res) {cout << s << "\n";}return 0;
};

单元测试

		TEST_METHOD(TestMethod01){string str = "abab";auto res = Solution().Ans(str);vector<string> ac{ "ab", "ba", "aba", "bab"};sort(ac.begin(), ac.end());AssertV(ac, res);}TEST_METHOD(TestMethod02){string str = "aaaaaa";auto res = Solution().Ans(str);vector<string> ac{ "a", "aa", "aaa", "aaaa", "aaaaa" };sort(ac.begin(), ac.end());AssertV(ac, res);}TEST_METHOD(TestMethod03){string str = "aaba";auto res = Solution().Ans(str);vector<string> ac{  "ab", "ba", "aab","aba"};sort(ac.begin(), ac.end());AssertV(ac, res);}

# 扩展阅读

我想对大家说的话
工作中遇到的问题,可以按类别查阅鄙人的算法文章,请点击《算法与数据汇总》。
学习算法:按章节学习《喜缺全书算法册》,大量的题目和测试用例,打包下载。重视操作
有效学习:明确的目标 及时的反馈 拉伸区(难度合适) 专注
闻缺陷则喜(喜缺)是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。
子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。
如果程序是一条龙,那算法就是他的是睛
失败+反思=成功 成功+反思=成功

视频课程

先学简单的课程,请移步CSDN学院,听白银讲师(也就是鄙人)的讲解。
https://edu.csdn.net/course/detail/38771
如何你想快速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
https://edu.csdn.net/lecturer/6176

测试环境

操作系统:win7 开发环境: VS2019 C++17
或者 操作系统:win10 开发环境: VS2022 C++17
如无特殊说明,本算法用**C++**实现。

http://www.xdnf.cn/news/14171.html

相关文章:

  • 原创无损智算OTN(HIC-OTN,Hitless Intelligent Computing OTN)
  • ar 导航导览技术如何实现的?室内外融合定位与ar渲染技术深度解析
  • Linux-线程
  • Component name “index“ should always be multi-word的解决方式
  • HarmonyOS应用开发——线性布局
  • python爬虫简便框架,附带百度操作完整案例
  • Transformer 核心概念转化为夏日生活类比
  • 自主导航巡检机器人系统解决方案
  • [智能客服project] 架构 | 对话记忆 | 通信层
  • UR机器人解锁关节扭矩控制:利用英伟达Isaac Lab框架,推动装配自动化的Sim2Real迁移
  • 自适应攻击的强大后门防御
  • 【AT32】AT32定时器
  • 【华为Pura 80 Ultra影像真的有点东西】
  • 批处理实现:自动抓取perfetto日志 自动导出到当前文件夹 自动打开分析页面
  • NLP学习路线图(四十四):跨语言NLP
  • 【Linux基础知识系列】第二十四篇-网络配置文件的解析与修改
  • error: error:0308010c:digital envelope routines::unsupported
  • 联想笔记本怎么装win11专业版_联想笔记本用u盘装win11专业版图文教程
  • 【BrowserTools MCP:让 AI 直接调试你的网页应用】
  • 深度学习笔记26-天气预测(Tensorflow)
  • 光伏功率预测 | RF随机森林多变量单步光伏功率预测(Matlab完整源码和数据)
  • react react-router-dom中获取自定义参数v6.4版本之后
  • 使用大模型预测甲状旁腺恶性肿瘤的研究报告
  • 2025年6月英语四级CET-4作文预测10篇7页PDF
  • 电路图识图基础知识-电动机的保护电路保护方式(二十六)
  • (题目向,随时更新)动态规划算法专题(2) --见识常见的尝试模型
  • centos 8.3(阿里云服务器)mariadb由系统自带版本(10.3)升级到10.6
  • AI与机器学习ML:利用Python 从零实现神经网络
  • 科技新底座揭幕!2025 MWC上海锚定AI+、5G融合、双区创新三大引擎
  • 扩展模块--QWebEngine功能及架构解析