剑指Offer面试题5:替换空格

#include <iostream>
using namespace std;

int main()
{
	char str1[] = "hello world";
	char str2[] = "hello world";

	char* str3 = "hello world";
	char* str4 = "hello world";

	if(str1 == str2)  //分配两个空间,复制内容,比较他们的地址
		cout << "str1 = str2" << endl;
	else
		cout << "str1 != str2" << endl;
	
	if(str3 == str4)  //无需分配内存,把它们指向"hello world"在内存中的地址
		cout << "str3 = str4" << endl;
	else
	    cout << "str3 != str4" << endl;
	
    return 0;
}

题目:把字符串中的每个空格替换成"%20"。例如,输入"We are happy."则输出"We%20are%20happy."。

#include <iostream>
#include <string>
using namespace std;

void ReplaceBlank(string& str)  //字符数组string的总容量,不是字符串长度或者字符个数	
{
	int actualLen = 0;  //字符数组实际长度
	int numBlank = 0;  //空格个数
	int i = 0;
	while(str[i] != '\0')  //遍历字符数组,统计长度
	{
		++ actualLen;

		if(str[i] == ' ')
			++ numBlank;

		++i;
	}
	int newLen = actualLen + numBlank * 2;
	str.resize(newLen);  //调整字符数组的大小
	int ptr_actual = actualLen - 1;
	int ptr_newLen = newLen - 1;
	while(ptr_actual >= 0 && ptr_newLen > ptr_actual)
	{
		if(str[ptr_actual] == ' ')
		{
			str[ptr_newLen --] = '0';
			str[ptr_newLen --] = '2';
			str[ptr_newLen --] = '%';
		}
		else
		{
			str[ptr_newLen --] = str[ptr_actual];
		}
		--ptr_actual;
	}
} 

int main() 
{	
    string Mystr = "We are happy.";
    ReplaceBlank(Mystr);
    cout << Mystr << endl;  // 输出替换空格后的字符串
    return 0;
}

解题思路:遍历字符串,遇到空格替换成%20,在原字符串上操作的基础上,若从前往后复制和替换,由于string不存在负索引会覆盖原始字符串中未替换的部分,先遍历找出原始长度和空格数量,新长度等于原始长度加上空格数量*2,用两个指针指向新字符串的末尾str[新长度]、str[原始长度],从后往前遍历,没遇到空格就复制,遇到空格就替换,直到结束。时间复杂度为O(n)。

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值