题目:定义一个函数,从第一个字符串中删除在第二个字符串中出现过的所有字符。例如,从第一个字符串”We are students.”中删除在第二个字符串”aeiou”中出现过的字符得到的结果是“W r stdnts.”。
我们可以利用一个哈希表将第二个字符串中出现的所有字符映射进去,这样就可以在O(1)的时间内判断出第一个字符串中的字符是否出现在第二个字符串中,同时可以在O(N)的时间内删除第二个字符串中出现的字符。
如果我们直接在原串上操作而不创建新的空间,那么就不需要开辟额外的空间。当第一个字符串中的字符在第二个字符串中没有出现时,直接在原串上进行覆盖即可。
#include<iostream>
using namespace std;
#include<string>
char* FirstDelSec(char *str1, char* str2)
{
char hashtable[256] = { 0 };
char* p = str1;
int sz2 = strlen(str2);
for (int i = 0; i < sz2; i++)
{
hashtable[str2[i]]++;
}
int index = 0;
while (*p != '\0')
{
if (hashtable[*p] == 0)
{
str1[index++] = *p;
}
p++;
}
str1[index] = '\0';
return str1;
}
int main()
{
char str1[] = " We are students";
char str2[] = "aeiou";
char* ret = FirstDelSec(str1, str2);
cout << ret << endl;
system("pause");
return 0;
}