PAT A1084 B1029 (甲级 乙级)

1084 Broken Keyboard (20)(20 分)

作者: CHEN, Yue

单位: PAT联盟

时间限制: 200ms

内存限制: 64MB

代码长度限制: 16KB

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.

Input Specification:

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.

Output Specification:

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

这道题难度不大,在甲级上通过率0.42,在乙级上通过率0.3,甲级的难度可能在英文上吧(哈哈,至少对我来说),不过结合示例和英文难度也不算大,case insensitive 是大小写不敏感,也就是包含大小写,然后输出只能输出大写。

这道题在《算法笔记》里边放在散列这一节,一开始没弄懂哪里散列,后来思考以后觉得大概就是在防重复这里用到了散列,首先枚举比对两个字符串,然后将不存在的字符变大写之后将其对应的int值作为下标记录到布尔数组当中,然后输出,再下次再检测到这个字符不存在的时候可以先查看布尔数组中有没有记录再决定是否输出。


AC代码

#include <cstdio>
#include <ctype.h>

int main() {
    char input[100], typeout[100];
    bool h[256] = {0};

    scanf("%s", input);
    scanf("%s", typeout);

    int j = 0;
    for(int i = 0; input[i] != '\0'; ++i, ++j) {
        while(typeout[j] != input[i]) {
            char c = toupper(input[i]);
            if(!h[(int)c]) {
                h[(int)c] = true;
                printf("%c", c);
            }
            ++i;
        }
        if(input[i] == '\0') {
            break;
        }
    }
    printf("\n");

    return 0;
}

在后边再多啰嗦两句这里我使用了 ctype 的库函数 toupper() 将字符变为大写

为防止这个toupper函数有什么意料之外的结果,特意去查了一下,防止被坑(算法题刷多了变得谨慎了些)

在ctype.h中 两个库函数 toupper() 、tolower() 的实现原型是这样的:


int tolower(int c)
{
	if ((c >= 'A') && (c <= 'Z'))
		return c + ('a' - 'A');
	return c;
}
 
int toupper(int c)
{
	if ((c >= 'a') && (c <= 'z'))
		return c + ('A' - 'a');
	return c;

可以看到如果不是字母将不会对其进行修改,看到这里就可以放心使用了。

当然也可以使用c++中的 cctype 达到同样的效果,但是别忘记 using namespace std;


若有错误,欢迎大家指摘。

猜你喜欢

转载自blog.csdn.net/CrazyOnes/article/details/81539841