PAT甲级真题 1112 Stucked Keyboard (20分) C++实现(键盘坏键问题)

题目

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 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

思路

vector stucked记录是否是坏键,初始化为-1;

坏键的特点是每次出现一定是k的整数倍个,一旦有一次不符合的,记录stucked[i] = 0,表示i一定不是坏键;如果符合,且stucked[i]仍是初始值-1,那么可以将其置为1,表示暂时相信i是坏键。

对字符串完成一次遍历,stucked[i] = 1的即为坏键。

输出时要求按出现顺序输出坏键,且只输出一次。第二次遍历字符串,用vector visited记录是否输出过坏键,遇到坏键且未输出过就将其输出;同时将正常应该出现的字符记录到ret里,在第二行打印出即可。

代码

#include 
#include 
using namespace std;

int main()
{
    int k;
    string s;
    cin >> k >> s;

    vector<int> stucked(128, -1);
    int i = 0;
    while (i<s.size()){
        bool flag = true;
        int j = i+1;
        while (j<s.size() && s[i]==s[j]) j++;
        if ((j-i) % k != 0){
            stucked[s[i]] = 0;
        }
        else if (stucked[s[i]]==-1) {
            stucked[s[i]] = 1;
        }
        i = j;
    }

    string ret = "";
    vector<bool> visited(128);
    i = 0;
    while (i<s.size()){
        ret += s[i];
        if (stucked[s[i]]){
            i += k - 1;
            if (!visited[s[i]]){
                cout << s[i];
                visited[s[i]] = true;
            }
        }
        i++;
    }
    cout << endl << ret;
    return 0;
}

你可能感兴趣的:(PAT)