pat 1050

本文介绍了一种用于找出两个字符串中不相似部分的算法。该算法首先将两个输入字符串进行排序,然后逐个比较字符并标记相同的字符以进行删除。最终输出的是第一个字符串中未被标记的部分,有效地实现了去除两字符串间共有的字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先将两个字符串排序,然后对应相同字符标记删除

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
bool flag[10001];
struct str{
    char ch;
    int index;
} str1[10001],str2[10001];

bool cmp_str(const struct str &a, const struct str&b){
    return a.ch < b.ch;
}

bool cmp_index(const struct str &a, const struct str &b){
    return a.index < b.index;
}
int main(){
    int i = 0;
    freopen("1.in", "r", stdin);
    while ((str1[i].ch = getchar()) != '\0'&&str1[i].ch != '\n'){
        str1[i].index = i;
        i++;
    }
    int len1 = i, len2;
    i = 0;
    while ((str2[i].ch = getchar()) != '\0'&&str2[i].ch != '\n'){
        str2[i].index = i;
        i++;
    }
    len2 = i;
    sort(str1, str1 + len1, cmp_str);
    sort(str2, str2 + len2, cmp_str);
    int j;
    i = j = 0;
    while (i < len1&&j < len2){
        if (str1[i].ch < str2[j].ch)
            i++;
        else if (str1[i].ch > str2[j].ch)
            j++;
        else if (str1[i].ch == str2[j].ch)
            {
                flag[str1[i].index] = true;
                i++;
            }
    }
    sort(str1, str1 + len1, cmp_index);
    for (i = 0; i < len1; i++)
        if (!flag[i])
            putchar(str1[i].ch);
    putchar('\n');
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值