1050 String Subtraction (20分)

本文介绍使用两种方法从一个字符串中去除所有在另一个字符串中出现的字符。第一种方法通过遍历检查,第二种方法利用哈希表实现O(1)时间复杂度的查找。

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

朴素方法直接查:

#include <iostream>
using namespace std;
string s1, s2;

bool check_exists(char c){
    for(auto a : s2){
        if(a == c)
            return true;
    }
    return false;
}
int main(){
    getline(cin, s1);
    getline(cin, s2);

    string res;
    for(auto c : s1){
        if(!check_exists(c))
            res += c;
    }

    cout << res << endl;
}

优化:
判断某个元素是否在某个集合出现过->哈希表 O(1)复杂度

#include <iostream>
#include <unordered_set>

using namespace std;

string s1, s2;

int main()
{
    getline(cin, s1);  
    getline(cin, s2);

    unordered_set<char> hash;  // 定义哈希表
    for (auto c : s2) hash.insert(c);  // 将s2中的字符插入哈希表

    string res;
    for (auto c : s1)
        if (!hash.count(c))  //count 统计哈希表中c的个数
            res += c;

    cout << res << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值