旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及实际被输入的文字,请你列出肯定坏掉的那些键。
输入格式:
输入在 2 行中分别给出应该输入的文字、以及实际被输入的文字。每段文字是不超过 80 个字符的串,由字母 A-Z(包括大、小写)、数字 0-9、以及下划线 _
(代表空格)组成。题目保证 2 个字符串均非空。
输出格式:
按照发现顺序,在一行中输出坏掉的键。其中英文字母只输出大写,每个坏键只输出一次。题目保证至少有 1 个坏键。
输入样例:
7_This_is_a_test
_hs_s_a_es
输出样例:
7TI
分析:
这道题不难,但是害苦了我。首先我又犯了以往的错误,把题想复杂了,一开始我考虑如果一个键有时输出有时不输出算不算坏键。后来发现这压根儿就不在题目范围内好吧!如果一个键是坏的,那么它根本就不会输出!总的来说整体思路很简单,对每一个s1的字符检索它是否在s2中,检查完后输出,注意大小写的问题。但我的代码写的特别复杂,如下:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char s1[100], s2[100];
int ptr1 = 0;
int disabled[100], cnt = 0, characters[26], nums[11];
memset(characters, 0, sizeof(characters));
memset(nums, 0, sizeof(nums));
cin >> s1 >> s2;
while(s1[ptr1] != '\0'){
//在s2中寻找对应字符
int i = 0;
while(s2[i] != '\0'){
if(s2[i] == s1[ptr1]) break;
else i++;
}
//没找到
if(s2[i] == '\0') disabled[cnt++] = ptr1;
ptr1++;
}
//输出
for(int i = 0; i < cnt; i++){
if(s1[disabled[i]] >= 'a' && s1[disabled[i]] <= 'z'){
if(characters[s1[disabled[i]] - 'a'] == 0){
char temp = s1[disabled[i]] - 32;
cout << temp;
characters[s1[disabled[i]] - 'a'] = 1;
}
}else if(s1[disabled[i]] >= 'A'&& s1[disabled[i]] <= 'Z'){
if(characters[s1[disabled[i]] - 'A'] == 0){
cout << s1[disabled[i]];
characters[s1[disabled[i]] - 'A'] = 1;
}
}else if(s1[disabled[i]] >= '0' && s1[disabled[i]] <= '9'){
if(nums[s1[disabled[i]] - '0'] == 0){
cout << s1[disabled[i]];
nums[s1[disabled[i]] - '0'] = 1;
}
}else if(s1[disabled[i]] == '_'){
if(nums[10] == 0){
cout << '_';
nums[10] = 1;
}
}
}
}
其中因为一个方括号的问题,卡了我很久很久!横竖不知道哪里错了,还不知道样例是什么,真让人捉急!后来在一个网站终于找到了样例,才发现程序的问题,竟然是少了一个方括号!我还纳闷这样其他的测试点竟然都能过!果然程序写复杂了真的不容易找其中的错误,看其他博客有十分简洁的代码:
#include<cstdio>
#include<cstring>
#include<cctype>
using namespace std;
int a[200] = {0};
int main(){
char str1[100], str2[100];
scanf("%s %s", str1, str2);
int len1 = strlen(str1), len2 = strlen(str2);
for(int i = 0; i < len2; i++)
a[toupper(str2[i])]++;
for(int i = 0; i < len1; i++){
a[toupper(str1[i])]--;
if(a[toupper(str1[i])] == -1) printf("%c", toupper(str1[i]));
}
}
其中toupper包含在<cctype>头文件中。