1. 程式人生 > >【PAT甲級】1084 Broken Keyboard(雜湊)

【PAT甲級】1084 Broken Keyboard(雜湊)

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

題目大意

這題就是說鍵盤壞了,然後第一行給出原本要輸出的字串,第二行給出實際輸出的字串 ,然後輸出壞掉的鍵盤字元。(不區分大小寫)。

個人思路

這題是【PAT乙級】的1029,看自己刷乙級題的程式碼簡直不忍直視什麼玩意,然後就重寫了一遍,幾行就ok了,我當時怎麼寫到七十幾行的。

這題輸入兩個字串s1,s2,建立一個bool型陣列is_broken,某個字元ascii碼對應其下標,陣列表示了某字元是否壞了。然後諸位比較兩個字串,如果字串的該位相等,則兩個字串都進入下一位,如果不相等,則s1標記當前字元壞了,如果是第一次壞就輸出,然後進入下一位。

程式碼實現

#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <iostream>
using namespace std;

// 轉化成大寫字母
void to_upper(string &s) {
    for (int i = 0; i < s.length(); i ++) {
        if (s[i] >= 'a' && s[i] <= 'z') s[i] += 'A'-'a';
    }
}

int main() {
    // 輸入
    string s1, s2;
    cin >> s1 >> s2;
    // 將鍵盤字母根據下標對映到is_broken上
    bool is_broken[200];
    memset(is_broken, 0, sizeof(is_broken));
    // 轉化成大寫字母
    to_upper(s1);
    to_upper(s2);
    // 逐位檢查
    for (int pos1 = 0, pos2 = 0; pos1 < s1.length(); pos1 ++) {
        if (s1[pos1] != s2[pos2] && !is_broken[s1[pos1]]) {
            cout << s1[pos1];
            is_broken[s1[pos1]] = true;
        }
        else if (s1[pos1] == s2[pos2]) pos2 ++;
    }
    return 0;
}

總結

學習不息,繼續加油