题目链接:https://www.nowcoder.com/practice/f0db4c36573d459cae44ac90b90c6212?tpId=85&&tqId=29868&rp=1&ru=/activity/oj&qru=/ta/2017test/question-ranking
题目描述
输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”
题目分析
根据题意,这里需要删除第一个字符串中的特定字符,这些字符是在第二个字符串中出现的。因此这里可以采用哈希映射的思想:设置一个固定大小的字符数组(因为这里的字符种类是有限的),字符串数组用来存放第二个字符串中各个字符的出现次数,字符的ASCLL码值为数组的下标。先定义一个新的输出的字符串,然后遍历第一个字符串,如果该字符在字符串数组对应的值为0,则可以插入返回的字符串,否则就跳过该字符。
代码实现
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1;
getline(cin, s1);//输入字符串s1
string s2;
getline(cin, s2);//输入字符串s2
size_t i = 0;
int hash[256] = { 0 };
string ret="";
for (i = 0; i < s2.size(); i++)
{
hash[s2[i]]++;
}
for (i = 0; i < s1.length(); i++)
{
if (hash[s1[i]] == 0)
{
ret += s1[i];
}
}
cout << ret << endl;
return 0;
}