【发布时间】:2020-08-31 18:53:07
【问题描述】:
给定一个包含重复字符和突发长度的字符串,输出字符串使得字符串中相同相邻字符的计数小于突发长度。
输入:abbccccdd,burstLen = 3
正确的输出:abbdd
我的输出:abbd
输入:abbcccdeaffff,burstLen = 3
正确的输出:abbdea
我的输出:abbea
//Radhe krishna ki jytoi alokik
#include <bits/stdc++.h>
using namespace std;
string solve(string s, int burstLen)
{
stack<pair<char, int>> ms;
for (int i = 0; i < s.size(); i++)
{
if (!ms.empty() && ms.top().first == s[i])
{
int count = ms.top().second;
ms.push({s[i], count + 1});
}
else
{
if(ms.empty() == true || ms.top().first != s[i])
{
if(!ms.empty() && ms.top().second >= burstLen)
{
int count = ms.top().second;
while(!ms.empty() && count--)
ms.pop();
//(UPDATE)
ms.push({s[i], 1});
}
else
ms.push({s[i], 1});
}
}
}
if(!ms.empty() and ms.top().second >= burstLen)
{
int count = ms.top().second;
while(!ms.empty() && count--)
ms.pop();
}
string ans = "";
while (!ms.empty())
{
ans += ms.top().first;
ms.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
int main()
{
string s;
int burstLen;
cin >> s;
cin >> burstLen;
cout << solve(s, burstLen) << "\n";
}
【问题讨论】:
-
小心
#include <bits/stdc++.h>和using namespace std;。他们只需几行代码就可以破坏程序。 -
我认为你过于复杂了。当您扫描字符串时,您可以计算您看到当前字符的次数。当您看到一个新字符时,如果计数小于突发长度,则将该字符添加到输出字符串中,重置计数器并开始处理新字符。
-
您的问题似乎缺少问题部分。您在寻找代码审查吗?
-
您的问题是什么?你的代码不符合你的要求吗?你得到编译器错误吗?请把它们包括在问题中。输出错误?请在问题中包含输入、输出和预期输出
-
是的,有点,我用笔和纸试了一下,但在某处我缺少一些条件,是的,需要帮助来解决这个问题。
标签: c++ string algorithm data-structures stack