《剑指Offer》面试题4:替换空格

《剑指Offer》面试题4:替换空格

知识点

    字符串。

    合并两个数组(包括字符串)时,如果从前往后复制每个数字(或字符)需要重复移动多次,那么可以考虑从后往前复制,这样就能减少移动的次数,从而提高效率。

题目描述

    请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,则输出“We%20are%20happy.”。

解题思路



测试用例


代码(原书)

/*《剑指Offer——名企面试官精讲典型编程题》代码
 著作权所有者:何海涛*/

#include "stdio.h"
#include <string>

/*length 为字符数组string的总容量*/
void ReplaceBlank(char string[], int length)
{
	if (string == NULL && length <= 0)
		return;

	/*originalLength 为字符串string的实际长度*/
	int originalLength = 0;
	int numberOfBlank = 0;
	int i = 0;
	while (string[i] != '\0')
	{
		++originalLength;

		if (string[i] == ' ')
			++numberOfBlank;

		++i;
	}

	/*newLength 为把空格替换成'%20'之后的长度*/
	int newLength = originalLength + numberOfBlank * 2;
	if (newLength > length)
		return;

	int indexOfOriginal = originalLength;
	int indexOfNew = newLength;
	while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
	{
		if (string[indexOfOriginal] == ' ')
		{
			string[indexOfNew--] = '0';
			string[indexOfNew--] = '2';
			string[indexOfNew--] = '%';
		}
		else
		{
			string[indexOfNew--] = string[indexOfOriginal];
		}

		--indexOfOriginal;
	}
}

void Test(char* testName, char string[], int length, char expected[])
{
	if (testName != NULL)
		printf("%s begins: ", testName);

	ReplaceBlank(string, length);

	if (expected == NULL && string == NULL)
		printf("passed.\n");
	else if (expected == NULL && string != NULL)
		printf("failed.\n");
	else if (strcmp(string, expected) == 0)
		printf("passed.\n");
	else
		printf("failed.\n");
}

// 空格在句子中间
void Test1()
{
	const int length = 100;

	char string[length] = "hello world";
	Test("Test1", string, length, "hello%20world");
}

// 空格在句子开头
void Test2()
{
	const int length = 100;

	char string[length] = " helloworld";
	Test("Test2", string, length, "%20helloworld");
}

// 空格在句子末尾
void Test3()
{
	const int length = 100;

	char string[length] = "helloworld ";
	Test("Test3", string, length, "helloworld%20");
}

// 连续有两个空格
void Test4()
{
	const int length = 100;

	char string[length] = "hello  world";
	Test("Test4", string, length, "hello%20%20world");
}

// 传入NULL
void Test5()
{
	Test("Test5", NULL, 0, NULL);
}

// 传入内容为空的字符串
void Test6()
{
	const int length = 100;

	char string[length] = "";
	Test("Test6", string, length, "");
}

//传入内容为一个空格的字符串
void Test7()
{
	const int length = 100;

	char string[length] = " ";
	Test("Test7", string, length, "%20");
}

// 传入的字符串没有空格
void Test8()
{
	const int length = 100;

	char string[length] = "helloworld";
	Test("Test8", string, length, "helloworld");
}

// 传入的字符串全是空格
void Test9()
{
	const int length = 100;

	char string[length] = "   ";
	Test("Test9", string, length, "%20%20%20");
}

int main()
{
	Test1();
	Test2();
	Test3();
	Test4();
	Test5();
	Test6();
	Test7();
	Test8();
	Test9();
	system("pause");
	return 0;
}

代码(牛客网)

class Solution {
public:
	void replaceSpace(char *str,int length) {
        if (str==NULL || length<=0)
            return;
        int originalLength=0;
        int numOfSpace=0;
        int i=0;
        while(str[i]!='\0')
        {
            ++originalLength;
            if(str[i]==' ')
                ++numOfSpace;
            ++i;
        }
        int newLength=originalLength+numOfSpace*2;
        if(newLength>length)
            return;
        int indexOfOrigin=originalLength;
        int indexOfNew=newLength;
        while(indexOfOrigin>=0 && indexOfNew>indexOfOrigin)
        {
            if(str[indexOfOrigin]==' ')
            {
                str[indexOfNew--]='0';
                str[indexOfNew--]='2';
                str[indexOfNew--]='%';
            }
            else
            {
                str[indexOfNew--]=str[indexOfOrigin];
            }
            --indexOfOrigin;
        }      
	}
};

相关题目1

    有两个排序数组A1和A2,内存在A1的末尾有足够多的空余空间容纳A2,实现一个函数,把A2中的所有数字插入到A1中并且所有的数字是排序的。


#include <iostream>
using namespace std;
void MerageArray(int *a1, int *a2, int a1Length, int a2Length, int a1Volume)
{
	//两个排序的数组a1和a2,它们的实际长度a1Length和a2Length,a1Volume为a1的总容量
	int merageLength = a1Length + a2Length;  //合并两个数组后的实际长度

	//边界检查  
	if (!a1 || !a2 || merageLength > a1Volume ||
		a1Length <= 0 || a2Length <= 0)
	{
		return;
	}

	int index = merageLength - 1; //用来指向a1或a2中元素要被复制到的位置  

	int a1Index = a1Length - 1; //指向a1中要复制元素的位置  

	int a2Index = a2Length - 1;//指向a2中要复制元素的位置  

	while (index >= 0 && a1Index >= 0 && a2Index >= 0)
	{
		//将两个数组中较大的元素复制
		if (a1[a1Index] > a2[a2Index])
		{
			a1[index] = a1[a1Index];         

			a1Index--;
		}
		else
		{
			a1[index] = a2[a2Index];

			a2Index--;
		}

		index--;
	}

	//当数组a1中的元素已复制完,但数组a2仍有元素,则将其依次复制到a1中
	while (index >= 0 && a2Index >= 0)
	{
		a1[index] = a2[a2Index];

		index--;

		a2Index--;
	}
}

int main()
{
	int a[10] = { 12, 13, 14, 15 };
	int b[6] = { 1, 4, 5, 9, 10 };
	int len1 = 4;
	int len2 = 5;
	MerageArray(a, b,len1,len2,10);
	for (int i = 0; i<len1 + len2; i++)
	{
		cout << a[i] << " ";
	}
	system("pause");
	return 0;
}


相关题目2【牛客网

将两个整型数组按照升序合并,并且过滤掉重复数组元素。

详细描述:

接口说明

原型:

voidCombineBySort(int* pArray1,int iArray1Num,int* pArray2,int iArray2Num,int* pOutputArray,int* iOutputNum);

输入参数:

int* pArray1 :整型数组1

intiArray1Num:数组1元素个数

int* pArray2 :整型数组2

intiArray2Num:数组2元素个数

输出参数(指针指向的内存区域保证有效):

int* pOutputArray:合并后的数组

int* iOutputNum:合并后数组元素个数

返回值:

void 

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

void CombineBySort(int* pArray1, int iArray1Num, int* pArray2, int iArray2Num, int* pOutputArray, int* iOutputNum)
{
	if (!pArray1 || !pArray2 || iArray1Num<0 || iArray2Num<0)
		return;
	int length1 = iArray1Num;
	int length2 = iArray2Num;
	set<int> CombineArray;
	int i = 0;
	for (i = 0; i<length1; i++)
	{
		CombineArray.insert(pArray1[i]);
	}
	for (i = 0; i<length2; i++)
	{
		CombineArray.insert(pArray2[i]);
	}
	set<int>::iterator iter;
	i = 0;
	for (iter = CombineArray.begin(); iter != CombineArray.end(); iter++)
	{
		pOutputArray[i++] = *iter;
	}
	*iOutputNum = CombineArray.size();
	CombineArray.clear();
}

int main()
{

	int iArray1Num = 0;
	int iArray2Num = 0;

	while (cin >> iArray1Num)
	{
		int pArray1[10000];
		int pArray2[10000];
		int pOutputArray[10000];
		int iOutputNum;
		int i = 0;

		while (i<iArray1Num)
		{
			cin >> pArray1[i++];
		}
		i = 0;

		cin >> iArray2Num;

		while (i<iArray2Num)
		{
			cin >> pArray2[i++];
		}

		CombineBySort(pArray1, iArray1Num, pArray2, iArray2Num, pOutputArray, &iOutputNum);

		for (i = 0; i<iOutputNum; i++)
		{
			cout << pOutputArray[i];
		}
		cout << endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值