1112 Stucked Keyboard (20 point(s))
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 Specification:
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 Specification:
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的倍数,则说明这个键盘字符可能损坏。结果记录在broken[]中。
2. 再次遍历字符串,输出损坏的按键,注意只输出一次,借助output[]实现。
3. 再次遍历字符串,若遇到损坏的键盘按键,则输出后,下标移动K位,否则移动1位。
本题思路巧妙。
#include<iostream>
#include<cstring>
using namespace std;
bool broken[256];
bool output[256];
int main(void){
int k;string s;cin>>k>>s;
int cnt;
for(int i=0;i<256;i++){
broken[i]=true;
output[i]=false;
}
for(int i=0;i<s.length();i++){
if(i==0) cnt=1;
else if(i>0&&s[i]==s[i-1]) cnt++;
else{
if(cnt%k!=0) broken[s[i-1]]=false;
cnt=1;
}
}
if(cnt%k!=0) broken[s[s.length()-1]]=false;
for(int i=0;i<s.length();i++){
if(broken[s[i]]&&!output[s[i]]){
cout<<s[i];
output[s[i]]=true;
}
}
cout<<endl;
for(int i=0;i<s.length();){
cout<<s[i];
if(broken[s[i]]) i+=k;
else i++;
}
return 0;
}