PAT B1029 旧键盘 (20point(s))

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

输入格式:

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

输出格式:

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

输入样例:

7_This_is_a_test
_hs_s_a_es

输出样例:

7TI
  • 思路 1:打表法(hash)
    两个指针同步遍历两个字符串,遇到不一样的开始处理:先把小写转大写,再c - '0',将字符转化为int映射到数组has[](初始化为0),若has[i] == 0打印出来,对应下标++;
  • code 1:
#include <string>
#include <iostream>
#include <stdio.h>
#include <cctype>	// *
using namespace std;
const int maxn = 128;
int has[maxn] = {0};
int main(){
	string s1, s2;
	cin >> s1 >> s2;
	int i = 0, j = 0;
	while(i != s1.size()){
		if(s1[i] == s2[j]){
			i++;j++;
		}
		else{
			if(islower(s1[i])) s1[i] = toupper(s1[i]);	//TIPS 1:
			int x = s1[i] - '0';
			if(has[x] == 0) printf("%c", s1[i]); 
			has[x]++;
			i++;
		}
	}
}
  • TIPS 1:
    ctype.h中的函数:
函数 功能 用法
islower(c) 判断c是否是小写字母 if(islower(c))
isupper(c) 判断c是否是大写字母 if(isupper(c))
toupper(c) 将c转化为大写(!!:返回的是int型) char c = toupper(c)
tolower(c) 将c转化为小写 char c = tolower(c)
isalpha(c) 大小写字母 -
isalnum(c) 大小写字母+数字 -
isblank(c) space、\t -
isspace(c) space、\t、\r、\n -
  • T2 code:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 255;
bool has[maxn];

int main(){
	string ori, real;
	cin >> ori >> real;
	for(int i = 0; i < real.size(); ++i){
		int x = (int)real[i];
		if(islower(real[i])) real[i] = toupper(real[i]);
		has[x] = true;
	}
	for(int i = 0; i < ori.size(); ++i){
		int x = (int)ori[i];
		if(islower(ori[i])) ori[i] = toupper(ori[i]);
		if(has[x] == false){
			printf("%c", ori[i]);
			has[x] = true;
		} 
	}
	return 0;
} 
发布了271 篇原创文章 · 获赞 5 · 访问量 6546

猜你喜欢

转载自blog.csdn.net/qq_42347617/article/details/104044784