版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:[https://blog.csdn.net/weixin\_42449444/article/details/91127875](https://blog.csdn.net/weixin_42449444/article/details/91127875)
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.
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, digital numbers 0-9, or _
(representing the space). It is guaranteed that both strings are non-empty.
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.
7_This_is_a_test
_hs_s_a_es
7TI
这题在PAT乙级中出现过:【PAT乙级】旧键盘,我当时是用python写的,读取输入的两行字符串s1,s2。如果s1中的字符没有在s2中出现,就把该字符的大写形式存入名为bad_key的list中,接下来对bad_key进行去重并输出,先利用set()来对bad_key()进行去重,然后再用list()将bad_key()转换回列表,在完成这个去重操作的同时,用sorted()函数来保留bad_key原有的顺序,最后用join把bad_key中所有的元素添加到一个空字符串中进行输出。
用C++来写的话,我的思路也是这样的,设预期输出的字符串为s1,实际输出的字符串为s2,遍历s2 将s2中的所有字符转换成大写后存入一个set中。将s1中的字符全部转换成大写形式后,无脑for-each遍历s1,若s1中的某个字符没有出现在set中,就说明这个键坏掉了 把它记录在输出结果ans中,最后输出ans即可。
s1,s2 = input(),input() #读取输入的俩行字符串
bad_key = [i.upper() for i in s1 if i not in s2] #若s1中的字符没有在s2中出现,就把该字符的大写形式存入名为bad_key的list中
print("".join(sorted(list(set(bad_key)),key=bad_key.index))) #这行是为了去除bad_key中的重复字符
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s1,s2;
getline(cin,s1); //预期输出的字符串s1
getline(cin,s2); //实际输出的字符串s2
set<char> s; //set用来存放实际输出的字符
for(int i = 0; i < s2.length(); i++) //遍历实际输出的字符串s2
{
s.insert(toupper(s2[i])); //将s2中的字符转换成大写后存入set中
}
transform(s1.begin(), s1.end(),s1.begin(),::toupper); //将s1中的字符全部转换成大写形式
string ans = ""; //ans用来存放坏掉的键,即输出结果
for(auto it : s1)
{
if(s.count(it) == 0) //若预期输出的字符实际上并没有输出,就将该字符记录在ans中
{
ans += it;
s.insert(it); //防止ans中出现重复的字符
}
}
cout << ans << endl;
return 0;
}