LeetCode-(two ideas) replace the spaces in the string with %20

Insert picture description here

#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996)

思路1:
遇到空格,就把后面的字符往后挪动两个位置。
问题:效率不高,时间复杂度O(N^2,所以不选用


思路2:
先遍历一遍计算出有多少个空格,再从前往后挪数据,把每个字符一步挪到位,
每个字符挪 spacenum*2.
遇到空格以后填%20,然后spacenum--;
时间复杂度为O(N);
选用思路2


代码如下:

void replaceSpace(char *str, int length)
{
    
    

	int spacenum = 0;
	int i = 0;

	for (; i < length; i++)
	{
    
    

		if (str[i] == ' ')
		{
    
    

			spacenum++;
			//i++;
		}
		
	}
	int end = length - 1;
	while (spacenum>0)
	{
    
    

			if (str[end] != ' ')
			{
    
    
				str[end + spacenum * 2] = str[end];
				end--;

			}
			else
			{
    
    
				str[end + spacenum * 2] = '0';
				str[end + spacenum * 2 - 1] = '2';
				str[end + spacenum * 2 - 2] = '%';
				end--;
				spacenum--;
			}
	}
}

Insert picture description here


int main()
{
    
    
	char arr[28] = "We are happy";
	int len = strlen(arr);
	replaceSpace(arr, len);
	printf("%s\n\n\n", arr);
	return 0;
}

运行结果:

Insert picture description here

Guess you like

Origin blog.csdn.net/cfk17829572643/article/details/115045294