【PAT甲級A1084】Broken Keyboard (20分)(c++)

小莊同學發表於2020-11-22

1084 Broken Keyboard (20分)

作者:CHEN, Yue
單位:浙江大學
程式碼長度限制:16 KB
時間限制:400 ms
記憶體限制:64 MB

On a broken keyboard, some of the keys are worn out. So when you type some sentences, the characters corresponding to those keys will not appear on screen.

Now given a string that you are supposed to type, and the string that you actually type out, please list those keys which are for sure worn out.

Input Specification:
Each input file contains one test case. For each case, the 1st line contains the original string, and the 2nd line contains the typed-out string. Each string contains no more than 80 characters which are either English letters [A-Z] (case insensitive), digital numbers [0-9], or _ (representing the space). It is guaranteed that both strings are non-empty.

Output Specification:
For each test case, print in one line the keys that are worn out, in the order of being detected. The English letters must be capitalized. Each worn out key must be printed once only. It is guaranteed that there is at least one worn out key.

Sample Input:

7_This_is_a_test
_hs_s_a_es

Sample Output:

7TI

題意:

第一行輸入準備打的字串,第二行輸入用鍵盤打出的字串,
找出壞掉的鍵盤,用大寫輸出。

思路:

將兩行字串全部改為大寫,然後遍歷第一行字串,若和第二行對不上,則該字元為破壞的鍵盤字元,並將第一行中的這個字元全部刪除,直到遍歷結束。(注意對比時上下兩行的對齊)。

參考程式碼:

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main() {
    string s1, s2, str;
    cin >> s1 >> s2;
    transform(s1.begin(), s1.end(), s1.begin(), ::toupper);
    transform(s2.begin(), s2.end(), s2.begin(), ::toupper);
    for (int i = 0; i < s1.length();) {
        if (s2[i] != s1[i]) {
            char temp = s1[i];
            str += s1[i];
            while (s1.find(temp) != string::npos)
                s1.erase(s1.find(temp), 1);
        } else i++;
    }
    cout << str;
    return 0;
}

如有錯誤,歡迎指正

相關文章