题目描述:
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.
输入格式:
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.
输出格式:
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.
输入样例:
3
caseee1__thiiis_iiisss_a_teeeeeest
输出样例:
ei
case1__this_isss_a_teest
题意:
当我们按下坏掉的键时,我们会连续输出k个相同的字母(或数字和_),给定一个键盘,其中至少有1个键是坏掉的,给出我们现在输出的语句,问坏掉的键有哪些(按检测到的顺序),以及输出如果键没有坏掉,其本该输出的语句。
思路:
1.将0-9,,a-z转换为相应的数字,再用这些数字来定义变量
2.依次检测输出语句中的字符,用pre和now是否相等来判断前面出现了多少个相同的字符,如果出现的字符数==k,这个字符键可能是坏掉的,如果有一次出现这个字符数不等于k,那么这个字符键肯定没有坏
3.为了能使最后一个或几个字符也得到检测,在输入语句后面加上不属于0-9,,a-z的任意字符,辅助判断
详见代码~
参考代码:
//A1112 Stucked Keyboard (20分)
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 50;
bool broken[maxn] = {false}; //0-9不变,_为10,a-z为11-36
bool isBroken[maxn];
bool isVisited[maxn] = {false};
int toNum(char ch){
int num;
if(ch >= '0' && ch <= '9') num = ch - '0';
else if(ch >= 'a' && ch <= 'z') num = ch - 'a' + 11;
else if(ch == '_') num = 10;
else num = 40; //末尾#
return num;
}
int main(){
fill(isBroken, isBroken + maxn, true);
int k;
scanf("%d", &k);
string ori;
cin >> ori;
ori = ori + "#"; //为了使最后1位或几位得到统计
int len = ori.size();
char pre = ori[0];
int cnt = 1;
for(int i = 1; i < len; i++){
char now = ori[i];
if(pre == now){
cnt++;
}else{
int pNum = toNum(pre);
if(isBroken[pNum] && cnt % k == 0){
broken[pNum] = true;
}else{
broken[pNum] = false;
isBroken[pNum] = false;
}
cnt = 1;
pre = now;
}
}
//按顺序输出broken的键
for(int i = 0; i < len - 1; i++){
char now = ori[i];
int nNum = toNum(now);
if(isVisited[nNum] == false && broken[nNum] == true){
printf("%c", now);
isVisited[nNum] = true;
}
}
printf("\n");
//输出本该输出的语句
for(int i = 0; i < len - 1; i++){
char now = ori[i];
int nNum = toNum(now);
printf("%c", now);
if(broken[nNum]) i = i + k - 1;
}
printf("\n");
return 0;
}