PAT 乙级 1029.旧键盘 C++/Java

题目来源

旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及实际被输入的文字,请你列出肯定坏掉的那些键。

输入格式:

输入在 2 行中分别给出应该输入的文字、以及实际被输入的文字。每段文字是不超过 80 个字符的串,由字母 A-Z(包括大、小写)、数字 0-9、以及下划线 _(代表空格)组成。题目保证 2 个字符串均非空。

输出格式:

按照发现顺序,在一行中输出坏掉的键。其中英文字母只输出大写,每个坏键只输出一次。题目保证至少有 1 个坏键。

输入样例:

7_This_is_a_test
_hs_s_a_es
 

输出样例:

7TI

分析:

题目要求英文只输出大写,所以先把接收的字符串转成大写,用 <algorithm> 的 transform() 将字符串转大写

将残缺的字符串保存到哈希表中,然后遍历完整的字符串,如果遍历到一个字符不在哈希表中,就加到哈希表里,同时输出该字符

 

C++实现:

#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;

int main() {
    string wholeStr;    // 完整的字符串
    string fragStr;        // 不完整的字符串

    cin >> wholeStr >> fragStr;

    transform(wholeStr.begin(), wholeStr.end(), wholeStr.begin(), ::toupper);
    transform(fragStr.begin(), fragStr.end(), fragStr.begin(), ::toupper);

    unordered_map<char, int> countMap;
    for (int i = 0; i < fragStr.length(); ++i) {
        if (countMap.find(fragStr[i]) == countMap.end()) {
            countMap[fragStr[i]] = 1;
        }
    }

    for (int i = 0; i < wholeStr.size(); ++i) {
        if (countMap.find(wholeStr[i]) == countMap.end()) {
            countMap[wholeStr[i]] = 1;
            cout << wholeStr[i];
        }
    }
    return 0;
}

 

 

 

Java实现:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner in = new Scanner(System.in);
 6         String should = in.nextLine();
 7         String real = in.nextLine();
 8         in.close();
 9         String out = "";
10         for (int i = 0; i < should.length(); i++) {             //.indexOf:此处意为只输出第一次检索到should与real相同的字符
11             if(real.indexOf(should.charAt(i)) == -1 && out.indexOf(Character.toUpperCase(should.charAt(i))) == -1){
12                 out += Character.toUpperCase(should.charAt(i));
13             }           //str.toUpperCase(): 将小写字符转为大写字符
14         }
15         System.out.println(out);
16     }
17 }

 

posted @ 2020-01-17 21:44  47的菠萝~  阅读(194)  评论(0编辑  收藏  举报