PAT 甲级 A1084

1084 Broken Keyboard (20分)

题目描述

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] (case insensitive), 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.

Sample Input:

7_This_is_a_test
_hs_s_a_es

Sample Output:

7TI

总结

  1. 由于输入的只有A-Z 26个字母(小写转化为大写即可),_和0-9不同的类型,共计37个字符,因此需要开一个大小为37的hashTable
  2. 借助散列的思想,将输出的实际序列的每个字符保存到一个hashTable中
  3. 最后遍历输入的字符,得到没有出现过的字符

AC代码

#include<iostream>
#include<cstring>
#include<ctype.h>
using namespace std;
int main() {  
	char in[85], out[85];
	scanf("%s%s", in, out);
	int len1 = strlen(in);
	int len2 = strlen(out);
	int hashTable[37] = { 0 };  //映射关系下标 0-9:'0'-'9',  _:10   A:11...Z:36
	char res[80];
	int num = 0;
	int i = 0, j = 0;
	while (j < len2) {
		char temp = toupper(out[j++]);
		if (isalpha(temp)) {  //是字母,大写字母出现次数加一
			hashTable[temp - 'A' + 11]++;
		}
		else if (temp == '_') {  //空格出现次数加一
			hashTable[10]++;
		}
		else if (isdigit(temp)) {//数字出现次数加一
			hashTable[temp - '0']++;
		}
	}

	while (i < len1) {
		char temp = toupper(in[i++]);
		if (isalpha(temp) && hashTable[temp - 'A' + 11] == 0) {  //当前字母没出现
			res[num++] = temp;
			hashTable[temp - 'A' + 11]++;  //标记出现
		}
		else if (temp == '_'&&hashTable[10] == 0) {  //空格键坏了,出现次数加1
			res[num++] = temp;
			hashTable[10]++;     //标记出现
		}
		else if (hashTable[temp - '0'] == 0 && isdigit(temp)) {// 数字键坏了
			res[num++] = temp;
			hashTable[temp - '0']++;
		}
	}
	
	for (int i = 0; i < num; i++) {
		printf("%c", res[i]);
	}
	return 0;
}
发布了16 篇原创文章 · 获赞 0 · 访问量 368

猜你喜欢

转载自blog.csdn.net/qq_38507937/article/details/104078507