解法1

#include <iostream>
using namespace std;
int main() {
    bool marked[256] = {false};  // 标记需要删除的字符
    string s1, s2;
    getline(cin, s1);
    getline(cin, s2);

    for (char c : s2) {
        marked[c] = true; // 若char c = 'a',则等价于 marked[97] = true
    }
    string result;
    result.reserve(s1.length());  // 预分配空间
    for (char c : s1) {
        if (!marked[c]) {
            result += c;
        }
    }
    cout << result << endl;
    return 0;
}

解法2

#include <iostream>
#include <unordered_set>
#include <string>
using namespace std;

int main() {
    string s1, s2;
    getline(cin, s1);  // 读取第一行输入 S1
    getline(cin, s2);  // 读取第二行输入 S2

    // 使用 unordered_set 存储 S2 中的字符
    unordered_set<char> charsToRemove;
    for (char c : s2) {
        charsToRemove.insert(c);
    }

    // 遍历 S1,删除 S2 中的字符
    string result;
    for (char c : s1) {
        if (charsToRemove.find(c) == charsToRemove.end()) {
            result += c;  // 如果字符不在 S2 中,则保留
        }
    }

    // 输出结果
    cout << result << endl;
    return 0;
}

一些心得:

  1. 字符类型 char 本质上是一个整数(ASCII 值),因此可以直接用作数组的索引。

  2. unordered_set 是 C++ 标准库中的一个容器,用于存储唯一元素(即不允许重复元素),并且提供高效的插入、删除和查找操作。它的底层实现基于哈希表(Hash Table),因此平均时间复杂度为 O(1)

  3. 哈希表由多个桶(Bucket)组成,每个桶可以存储一个或多个元素。

  4. 类似的一个概念是 set,它的底层实现是基于红黑树的,元素之间有序排列,平均时间复杂度为 O(logN)


拓展:unordered_set的一些用法

#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
    // 创建一个 unordered_set
    unordered_set<int> s;

    // 插入元素
    s.insert(10);
    s.insert(20);
    s.insert(30);
    s.insert(10);  // 重复元素,不会被插入

    // 遍历元素
    cout << "Elements in unordered_set: ";
    for (int x : s) {
        cout << x << " ";
    }
    cout << endl;

    // 查找元素
    if (s.find(20) != s.end()) {
        cout << "Element 20 found!" << endl;
    }

    // 删除元素
    s.erase(20);
    cout << "After erasing 20, elements: ";
    for (int x : s) {
        cout << x << " ";
    }
    cout << endl;

    // 检查元素是否存在
    if (s.count(30)) {
        cout << "Element 30 exists!" << endl;
    }

    return 0;
}
输出:
Elements in unordered_set: 30 20 10 
Element 20 found!
After erasing 20, elements: 30 10 
Element 30 exists!