题目大意:给出一个字符串,由于某些键坏了,表现在按一次这个键就会出现K个重复的字符。判断哪些键可能坏了,并且输出剔除因为坏键而多输出的字符。
核心问题是找到字符串中的重复出现字符,并且长度是K的整数倍,那么就可能是坏键。反之,如果有字符出现的长度不是K的整数倍,说明一定不是坏键。因此,遍历字符串,找到每个字符出现的长度,如果模K不为0,说明一定不是坏键,没有被排除的就可能是坏键。最后剔除多输出的字符时要注意,每K个重复字符只输出1个,不是所有重复字符只输出1个。
坑点在于不是坏键的条件是出现的长度模K不为0,而不是长度小于K(测试点2)。
AC代码:
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
int main()
{
int k;
scanf("%d\n", &k);
string str;
getline(cin, str);
vector<bool> isNotStucked(256, 0);
for (int i = 0; i < str.size(); ++i)
{
int cnt = 1;
if(i < str.size() - 1 && str[i] == str[i+1])
{
while(i < str.size() - 1 && str[i] == str[i+1])
{
cnt++;
i++;
}
}
if(cnt % k != 0) isNotStucked[str[i]] = true;
}
string stuckedKeys, ans;
vector<bool> added(256, 0);
for (int i = 0; i < str.size(); ++i)
{
if(isNotStucked[str[i]]) ans += str[i];
else
{
ans += str[i];
if(!added[str[i]])
{
stuckedKeys += str[i];
added[str[i]] = true;
}
i += k - 1;
}
}
cout << stuckedKeys << endl;
cout << ans << endl;
return 0;
}