当前位置: 代码迷 >> 综合 >> 个人练习-PAT甲级-1084 Broken Keyboard
  详细解决方案

个人练习-PAT甲级-1084 Broken Keyboard

热度:80   发布时间:2023-12-21 11:14:21.0

题目链接https://pintia.cn/problem-sets/994805342720868352/problems/994805382902300672

简单题,但第一次做的时候不知道为什么最后一个点一直过不去。于是干脆多开几个记录数组,都遍历一遍,然后就过了。

先扫描s2(短的字符串),若某个字符有,就将其对应isIn[]置为true

    string s1, s2;vector<char> ret;bool isIn[37] = {
     false };bool inRet[37] = {
     false };cin >> s1 >> s2;for (int i = 0; i < s2.size(); i++) {
    char tmp = s2[i];if (tmp >= 'a' && tmp <= 'z')tmp += 'A' - 'a';else;Insert(isIn, tmp);}

然后扫描s1,如果s1中有而s2中没有,就将其放入ret数组中,并置inRet对应的字符的值为true,防止重复放入ret数组

    for (int i = 0; i < s1.size(); i++) {
    char tmp = s1[i];if (tmp >= 'a' && tmp <= 'z')tmp += 'A' - 'a';else;if (!Read(isIn, tmp) && !Read(inRet, tmp)) {
    ret.push_back(tmp);Insert(inRet, tmp);}}

读取和置值的两个函数如下,都是放入大小为37的数组和字符就行

void Insert(bool isIn[], char tmp) {
    if (tmp >= '0' && tmp <= '9')isIn[tmp - '0'] = true;else if (tmp >= 'A' && tmp <= 'Z')isIn[tmp - 'A' + 10] = true;elseisIn[36] = true;
}bool Read(bool isIn[], char tmp) {
    if (tmp >= '0' && tmp <= '9')return isIn[tmp - '0'];else if (tmp >= 'A' && tmp <= 'Z')return isIn[tmp - 'A' + 10];elsereturn isIn[36];
}

完整代码

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<map>
#include<set>
#include<queue>
#include<string.h>using namespace std;void Insert(bool isIn[], char tmp) {
    if (tmp >= '0' && tmp <= '9')isIn[tmp - '0'] = true;else if (tmp >= 'A' && tmp <= 'Z')isIn[tmp - 'A' + 10] = true;elseisIn[36] = true;
}bool Read(bool isIn[], char tmp) {
    if (tmp >= '0' && tmp <= '9')return isIn[tmp - '0'];else if (tmp >= 'A' && tmp <= 'Z')return isIn[tmp - 'A' + 10];elsereturn isIn[36];
}int main() {
    string s1, s2;vector<char> ret;bool isIn[37] = {
     false };bool inRet[37] = {
     false };cin >> s1 >> s2;for (int i = 0; i < s2.size(); i++) {
    char tmp = s2[i];if (tmp >= 'a' && tmp <= 'z')tmp += 'A' - 'a';else;Insert(isIn, tmp);}for (int i = 0; i < s1.size(); i++) {
    char tmp = s1[i];if (tmp >= 'a' && tmp <= 'z')tmp += 'A' - 'a';else;if (!Read(isIn, tmp) && !Read(inRet, tmp)) {
    ret.push_back(tmp);Insert(inRet, tmp);}}for (int i = 0; i < ret.size(); i++)printf("%c", ret[i]);return 0;
}
  相关解决方案