当前位置: 代码迷 >> 综合 >> PAT - 甲级 - 1112. Stucked Keyboard (20) (STL - vector)
  详细解决方案

PAT - 甲级 - 1112. Stucked Keyboard (20) (STL - vector)

热度:24   发布时间:2023-10-09 15:38:15.0

题目描述:

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个字母被敲击出来。

那么好的键连续出现的次数一定不是k的倍数,只要遍历一次字符串,标记连续出现的次数不是k的倍数的字符即可。

需要注意的是最后一个字符的处理。

题目代码:

#include <cstdio>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int k;
string s;
vector<int>v(500); // 一定好的键盘 
vector<int>vis(500); // 访问过的坏键盘 
int main(){scanf("%d",&k);cin>>s;for(int i = 0; i < s.length(); i++){v[s[i]] = 0; // 初始化vis[s[i]] = 0; } char per = '#';s = s + "#";int cnt = 1;for(int i = 0; i < s.length(); i++){if(s[i] == per){cnt++;}else{if(cnt % k) // 连续出现次数不是k的倍数 v[per] = 1; // 一定好 cnt = 1;}per = s[i];}//输出坏键 for(int i = 0; i < s.length()-1; i++){if(v[s[i]] == 0 && vis[s[i]] == 0){cout<<s[i];vis[s[i]] = 1;}}cout<<endl;for(int i = 0; i < s.length()-1; i++){ // 输出想要输出的内容 cout<<s[i];if(v[s[i]] == 0)i += k-1;} return 0;
} 


  相关解决方案