Home Pat 1534 字符串减法
Post
Cancel

Pat 1534 字符串减法

题目

给定两个字符串 S1 和 S2,S=S1−S2 定义为将 S1 中包含的所有在 S2 中出现过的字符删除后得到的字符串。

你的任务就是计算 S1−S2。

输入格式

共两行,第一行包含字符串 S1,第二行包含字符串 S2。

输出格式

输出共一行,表示 S1−S2 的结果。

数据范围

两个给定字符串的长度都不超过 104。

输入样例:

1
2
They are students.
aeiou

输出样例:

1
Thy r stdnts. 


题解

  1. 解法1

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
     #include <iostream>
     using namespace std;
     int main()
     {
         string s1, s2, s3;
         getline(cin, s1);
         getline(cin, s2);
         for (auto s : s1) {
             auto idx = s2.find(s);
             if(idx == string::npos) {
                 s3.push_back(s);  // s3 += c
             }
         }
         cout << s3 << endl;
         return 0;
     }
        
    
  2. 使用哈希集合的解法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
     #include <iostream>
     #include <unordered_set>
     using namespace std;
     int main()
     {
         string s1, s2, s3;
         getline(cin, s1);
         getline(cin, s2);
            
         unordered_set<char> hash;
         for (auto c : s2) hash.insert(c);
            
         for (auto c : s1) {
             if (!hash.count(c)) {
                 s3 += c;
             }
         }
         cout << s3 << endl;
         return 0;
     }
    
This post is licensed under CC BY 4.0 by the author.
Contents