String Subtraction

题目描述:

Given two strings S1 and S2, S = S1 - S2 is defined to be the remaining string after taking all the characters in S2 from S1. Your task is simply to calculate S1 - S2for any given strings. However, it might not be that simple to do it fast.


 

输入:

Each input file contains one test case. Each case consists of two lines which gives S1 and S2, respectively. The string lengths of both strings are no more than 10000. It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.


 

输出:

For each test case, print S1 - S2 in one line.


 

样例输入:

They are students.

aeiou


 

样例输出:

Thy r stdnts.


 

这道题就是对字符串做操作。刚看这题的时候,就是要把原字符串中的一些字符删掉,但真的有那么好删吗?

我们不妨换个思路。对于第二个短一些的字符串,我用一个数组(默认值全部为0)把每个字符存起来,然后再遍历原字符串。在遍历的时候,一旦发现这个数组里面对应的字符是1,我就不输出。这样就十分巧妙。(注意,很多地方都有用到这种方法,用一个数组存一些值的这种方法一定要会灵活利用!)

来看看代码:

 1 #define _CRT_SECURE_NO_WARNINGS 1
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstdlib>
 5 #include <cstring>
 6 using namespace std;
 7 char str1[100000];
 8 char str2[100000];
 9 char ch, c;
10 int flag[10000] = { 0 };
11 int main()
12 {
13     while (gets(str1))
14     {
15         gets(str2);
16         for (int i = 0; i < strlen(str2); ++i) {
17             ch = str2[i];
18             flag[ch] = 1;
19         }
20         for (int i = 0; i < strlen(str1); ++i) {
21             c = str1[i];
22             if (flag[c] == 0) {
23                 printf("%c", c);
24             }
25         }
26         memset(flag, 0, sizeof(flag));
27         printf("\n");
28     }
29     return 0;
30 }

String Subtraction

 

 注意一下,用VS 2019的话,gets函数要换成gets_s.否则会报错。

上一篇:String常用方法


下一篇:07-13