PAT乙级1033

247 阅读2分钟

题目:

旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及坏掉的那些键,打出的结果文字会是怎样?

输入格式:

输入在 2 行中分别给出坏掉的那些键、以及应该输入的文字。其中对应英文字母的坏键以大写给出;每段文字是不超过 10^5个字符的串。可用的字符包括字母 [a-z, A-Z]、数字 0-9、以及下划线 _(代表空格)、,、.、-、+(代表上档键)。题目保证第 2 行输入的文字串非空。

注意:如果上档键坏掉了,那么大写的英文字母无法被打出。

输出格式

在一行中输出能够被打出的结果文字。如果没有一个字符能被打出,则输出空行。

思路

输入两组到string,然后要用到find函数,toupper函数,isupper函数。find函数是我们的老朋友了,查找在某个字符串中是否存在某个字串,没有则返回特殊值npos.而toupper则是将小写字母转化为大写字母的函数。isupper是简单的判断是否是大写字母。

先进行判断error串中是否存在上档键'+',存在的话就不能输出大写,再判定error中与s中小写及其他字符。因为error其中对应英文字母的坏键以大写给出 ,所以使用toupper函数转化一下再进行find.上档键没坏的话直接对每个字符进行判定就好,不再在意大小写。

//foreverking
#include <vector>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;

string error, s;

int main(){
    
	getline(cin, error);
	getline(cin, s);
    //上档键坏了
    if(error.find('+') != error.npos){
        for(int i = 0; i < s.size(); i++){//不能输出大写,大写一律不要
            if(!isupper(s[i]) && error.find(toupper(s[i])) ==error.npos)
                cout << s[i];
        }
    }
    //上档键没坏,可以输出大写
    else {
        for(int i = 0; i < s.size(); i++){//出现在error的不要
            if(error.find(toupper(s[i])) == error.npos)
                cout << s[i];
        }
    }

    cout << endl;
    return 0;
}

优化一下,直接遍历s串,每次都判定一下上档键是否坏了,坏了就不输出大写,直接continue.还有一个是判定是判断小写及其他字符是否能输出。

//foreverking
#include <vector>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;


string error,s;
int main(){
    getline(cin, error);
    getline(cin, s);
    for(int i = 0; i < s.length(); i++) {
        if(error.find(toupper(s[i])) != error.npos) 
            continue;//找到对应大写,键坏了,不能输出
        if(isupper(s[i]) && error.find('+') != error.npos) 
            continue;//上档键坏了,不能输出大写,但是s中有的字母偏偏是大写,所以不能输出

        cout << s[i];
    }

    cout << endl;
    return 0;
}

记住输出的时候使用string头文件中的getline,可以输入一行。 题目链接