A 1112 Stucked Keyboard
Problem Description
On a broken keyboard, some of the keys are always stucked. So when you type some sentences, the characters corresponding to those keys will appear repeatedly on screen for k times.
Now given a resulting string on screen, you are supposed to list all the possible stucked keys, and the original string.
Notice that there might be some characters that are typed repeatedly. The stucked key will always repeat output for a fixed k times whenever it is pressed. For example, when k=3, from the string thiiis iiisss a teeeeeest
we know that the keys i
and e
might be stucked, but s
is not even though it appears repeatedly sometimes. The original string could be this isss a teest
.
Input
Each input file contains one test case. For each case, the 1st line gives a positive integer k (1<k≤100) which is the output repeating times of a stucked key. The 2nd line contains the resulting string on screen, which consists of no more than 1000 characters from {a-z}, {0-9} and _. It is guaranteed that the string is non-empty.
Output
For each test case, print in one line the possible stucked keys, in the order of being detected. Make sure that each key is printed once only. Then in the next line print the original string. It is guaranteed that there is at least one stucked key.
Sample Input:
3
caseee1__thiiis_iiisss_a_teeeeeest
Sample Output:
ei
case1__this_isss_a_teest
题目大意:
键盘坏了,按下某一个键,会自动再次重复这个键k-1次。找出所有坏了的键位,然后输出正确的打印内容。
解题思路:
先找坏了的键,统计每一个键位连续出现的次数,如果某个键每次出现的连续次数都大于等于k且次数是k的整数倍,那么说明这个键位坏了。再次遍历字符串,每遇到这个键位一次,删除其后面的k-1个位置。完事后的字符串就是正确的打印内容。
AC代码
#include<bits/stdc++.h>
using namespace std;
int magic(char x){
if('0'<=x && x<='9'){
return x-'0';
}else if('a'<=x && x<='z'){
return (x-97)+10;
}
return 40;
}
int main(){
string str;
int vis[45],flag[45],k,now,num=0;
char c;
fill(vis,vis+45,1);
fill(flag,flag+45,0);
scanf("%d",&k);
cin>>str;
for(int i=0,len=str.size();i<len;){
c=str[i];
num=0;
now=magic(c);
while(str[i]==c){
num++;
i++;
}
if(num<k || num%k!=0) vis[now]=0;
}
for(int i=0,len=str.size();i<len;i++){
now=magic(str[i]);
if(vis[now] && !flag[now]){
printf("%c",str[i]);
flag[now]=1;
}
}
printf("\n");
for(int i=0;i<str.size();i++){
now=magic(str[i]);
if(vis[now]){
str.erase(str.begin()+i+1,str.begin()+i+k);
}
}
printf("%s",str.c_str());
return 0;
}