目的:找出键盘坏掉的键,还原原本的输入
输入:
K 坏的键重复的次数
输入的字符串
输出:
坏掉的键,按照字符串中出现的顺序输出
还原的输入字符串
算法:
用unordered_map<char,bool> hash1存字符,遍历字符串
1.当前字符,先判断包括该字符在内的后面这K个字符是否是一样的,一样跳转2,不一样跳转3
2.若该字符在hash1中不存在,那么就先存入,且为true。若hash1中原本有了,就保持这个不变。同时遍历往前跳跃K-1,跳过这K个字符。
3.无论hash1中该字符存不存在,置为false。再遍历下一个字符
4.重复1
这样就把所有字符串中的字符是坏还是好的都确定了。
重新遍历字符串,若hash1中为true,输出。
再遍历字符串,若为false,输出字符,若为true,输出字符,往前跳跃K-1个
#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
unordered_map<char,bool> hash1;
string str;
int K;
int main()
{
cin>>K>>str;
char c = str[0];
int cnt = 0;
for(int i=0;i<str.size();i++)
{
if(c==str[i])
{
cnt++;
}else
{
if(cnt%K==0)
{
if(hash1.find(c)==hash1.end())
hash1[c] = true;
}else
{
hash1[c] = false;
}
c = str[i];
cnt = 1;
}
}
if(cnt%K==0)
{
if(hash1.find(c)==hash1.end())
hash1[c] = true;
}else
{
hash1[c] = false;
}
unordered_map<char,bool> hash2 = hash1;
for(int i=0;i<str.size();i++)
{
if(hash2[str[i]]==true)
{
hash2[str[i]] = false;
i = i+K-1;
cout<<str[i];
}
}
cout<<endl;
for(int i=0;i<str.size();i++)
{
if(hash1[str[i]]==true)
{
i = i+K-1;
}
cout<<str[i];
}
cout<<endl;
return 0;
}