PAT甲級真題1112 Stucked Keyboard(20点)C++実現(キーボードの不良キーの問題)

9455 ワード

タイトル
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のままである場合、iが不良キーであると一時的に信じることを示す1に設定することができる.
文字列の遍歴が完了すると、stucked[i]=1は悪いキーになります.
出力時には出現順に不良キーを出力し、一度だけ出力する必要があります.2回目の遍歴文字列は、vector visitedで不良キーを出力したかどうかを記録し、不良キーに遭遇し、出力しなかった場合に出力する.同時に正常に現れるべき文字をretに記録し、2行目に印刷すればよい.
コード#コード#
#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;
}