【牛客网】 字符串习题练习

**题目表述:**删除一个字符串中,另一个字符串的所有字符。
例如: str1: they are students.
str2: arinu
输出: thy e stdets.

//题目描述:找出一个字符串中另一个字符串的所有字符

//方法一:使用string容器的方法来简单实现
#if 0
int main()
{
	char buf[1024];
	cin.getline(buf, 1023);
	string src = buf;
	cin.getline(buf, 1023);
	string dsc = buf;

	for (int i = 0; i < dsc.size(); ++i)
	{
		char c = dsc[i];
		while (src.find(c) != string::npos)
		{
			src.erase(src.begin() + src.find(c));
		}
	}
	cout << src;
	return 0;
}
#endif


//方法二:利用哈希思想
//字符共有256个,将第二个字符串的所有字符在一个数组arr中标记为1,不存在的字符标记为0,
//利用快慢指针便利第一个字符串,如果*fast在arr中不存在,也就是说不在第二个字符串中的字符,就覆盖*slow,如果存在fast向后移动。
#include<iostream>
#include<string>
using namespace std;

void fun(char* _s1, char* _s2)
{
	if (_s1 == nullptr)
		return;
	if (_s1 != nullptr && _s2 == nullptr)
		return;
	int arr[256] = { 0 };
	char* cur = _s2;
	char* fast = _s1;
	char* slow = _s1;
	//设置哈希表
	while (*cur != '\0')
	{
		arr[*(cur++)] = 1;
	}
	while (*fast != '\0')
	{
		//保留不用删除的字符
		if (arr[*fast] != 1)
		{
			*slow = *fast;
			fast++;
			slow++;
		}
		//删除
		else
		{
			fast++;
		}
	}
	*slow = '\0';
	return;
}

int main()
{
	char s1[256] = { 0 };
	char s2[256] = { 0 };
	
	cin.getline(s1, 256);
	cin.getline(s2, 256);
     fun(s1, s2);
	cout << s1 << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值