(PAT)1084 Broken Keyboard(哈希表)

忘是亡心i 2022-05-10 04:42 287阅读 0赞

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:

  1. 7_This_is_a_test
  2. _hs_s_a_es

Sample Output:

解题思路:

构建一个哈希表,将各字符的ASCII值作为键码传入到哈希表中,并标记这个键值标签下的ASCII值为true或为false

第一次输入将所有字符都标记为true

第二次输出将所有字符都标记为false,这样剩下的标记为true的字符就表示没有正常输出的字符

最后输出标记为true的字符即可

代码:

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main() {
  5. string strinput; //输入字符串
  6. string stroutput; //输出字符串
  7. bool hashTable[258] = { false }; //记录输入和输出操作
  8. int hashIndex[258] = { 0 };
  9. int index = 0;
  10. cin >> strinput;
  11. cin >> stroutput;
  12. for (auto &x : strinput) {
  13. if (isalpha(x)) {
  14. x = toupper(x); //转为大写
  15. }
  16. int code = (int)x; //char类型到int类型
  17. hashTable[code] = true; //表示进行了一次敲击
  18. hashIndex[index] = code;
  19. index++;
  20. }
  21. for (auto &y : stroutput) {
  22. if (isalpha(y)) {
  23. y = toupper(y); //转为大写
  24. }
  25. int code = (int)y;
  26. hashTable[code] = false;
  27. }
  28. for (int code = 0; code < index; ++code) { //遍历操作
  29. if (hashTable[hashIndex[code]]==true) { //敲打过的
  30. char bet = char(hashIndex[code]); //将ACSCII码转为字符
  31. cout << bet;
  32. hashTable[hashIndex[code]] = false;
  33. }
  34. }
  35. return 0;
  36. }

发表评论

表情:
评论列表 (有 0 条评论,287人围观)

还没有评论,来说两句吧...

相关阅读

    相关

    我们知道,通过对数组进行直接寻址(Direct Addressing),可以在 O(1) 时间内访问数组中的任意元素。所以,如果存储空间允许,可以提供一个数组,为每个可能的关键

    相关

    一、简介 如果所有的键都是小整数,那么我们可以用一个数组来实现无序的符号表,将键作为数组的索引i而数组中i(键)处储存的就是对应的值。 这样就可以快速地访问任意键的值,

    相关

    【一】哈希表 > 他通过把关键码值映射到表中的一个位置来访问记录,以加快查找的速度。这个映射函数就是散列函数。 ![watermark_type_ZmFuZ3poZW5na