LeetCode 笔试题 字符串空格替换

问题描述

将 “we are happy”中的空格替换为“%20”。

即输入“we are happy”

输出“we%20are%20happy”

代码一

//如果直接遍历碰到空格,后面所有的往后移动,则徒劳的移动太多,
//目标:所有的字符串一次移动到位,移动最少
//1.统计空格的数量
//2.确定直接就在原来的字符串上移动,节省空间
//3.确定从前往后遍历(需要新开字符串),还是从后往前遍历(不用新开,从后往前没一个字符串都是一次移动到位)
void Replace(char *str, int len)
{
	assert(str != NULL);
	int count = 0;
	char *p = str;
	int lenChar = 0;
	//统计空格数目
	while (*p != '\0')
	{
		if (*p == ' ')
		{
			count++;
		}
		lenChar++;
		p++;
	}
	int newlen = count * 2 + lenChar;
	if (newlen > len)
	{
		return;
	}
	int i = lenChar;
	int j = newlen;
	while (i >= 0 && j >=0)
	{
		if (str[i] == ' ')
		{
			str[j--] = '0';
			str[j--] = '2';
			str[j--] = '%';
		}
		else
		{
			str[j--] = str[i];
		}
		i--;
	}

}
int main()
{
	char str[100] = " a  sl  awql   dwle   awq   ";
	Replace(str, 100);
	printf("%s\n", str);
	getchar();
	return 0;
}

代码二:利用近容器string及其相关函数 

void Replace(string &str)
{
	/*
	遍历str
	若为空格 erase空格  分别insert % 2 0;
	注意!!!  迭代器失效问题 每次 erase或insert都要用it保存返回值
	由于是在当前位置插入 因此要 0  2 % 这样插入  然后it要向后偏移3个,跳过%20 进行遍历
	*/
	auto it = str.begin();
	while (it != str.end())
	{
		if (*it == ' ')
		{
			it = str.erase(it);
			it = str.insert(it, '0');
			it = str.insert(it, '2');
			it = str.insert(it, '%');
			it += 3;
		}
		else
		{
			++it;
		}
	}
}
int main()
{
	string str = "we are happy";
	Replace(str);
	for (char val : str)
	{
		cout << val;
	}
	cout << endl;
	getchar();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值