1050 String Subtraction (20分)
-----题目地址-----
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 −S2 for any given strings. However, it might not be that simple to do it fast.
Input Specification:
Each input file contains one test case. Each case consists of two lines which gives S1and S2 , respectively. The string lengths of both strings are no more than 10^4 . 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.
Output Specification:
For each test case, print S1 − S2 in one line.
Sample Input:
They are students.
aeiou
Sample Output:
Thy r stdnts.
作者 CHEN, Yue 单位 浙江大学
思路总结:
直接对字符串做删除操作显然有点麻烦,实际可以用散列的思想使问题得到简化。
①做散列表bool H[200]
,初始状态均为false
。
②遍历字符串2 : str
, 对字符串2
中的每个字符str[i]
,令H[str[i]-'\0'] = true
(直接写H[str[i]] = true
也没问题),表示该字符出现过。
③遍历字符串1: all
, 对all
中每个字符, 若该字符在散列表H
中未出现也即false
, 则输出,反之不输出。
AC代码:
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;
string all, str;
bool H[200] = {false};
int main()
{
getline(cin, all);
getline(cin,str);
for(int i=0; i<str.length(); i++){
int key = str[i] - '\0';
H[key] = true;
}
for(int i=0; i<all.length(); i++){
int key = all[i] - '\0';
if(H[key] == false){
printf("%c",all[i]);
}
}
return 0;
}