替换空格,思想从后往前

问题描述

将一个字符串中的空格替换成 “%20”。

Input:
"We Are Happy"
Output:
"We%20Are%20Happy"

解题思路

  1. 在原字符串地址空间进行操作,length(新)>length(旧),来节省空间
  2. 利用char*字符串的 ‘\0’ 来完成遍历,求取新字符串长度
  3. 令 P1 指向字符串原来的末尾位置,P2 指向字符串现在的末尾位置。P1 和 P2 从后向前遍历,当 P1 遍历到一个空格时,就需要令 P2 指向的位置依次填充 02%(注意是逆序的),否则就填充上 P1 指向字符的值。
    从后向前遍是为了在改变 P2 所指向的内容时,不会影响到 P1 遍历原来字符串的内容。

代码

main()中用到了char* 内存空间的分配问题

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

// 思路
//1:从前往后插入,这样移动·的次数多不建议
//2:从后往前插入
class Solution {
public:
		void repalceSapce(char *str, int length)
	{
		if (str == nullptr || length <= 0)
			return;
		int i = 0;
		int spaceNum = 0;
		int len = 0;
		while (str[i] != '\0')
		{
			if (str[i] == ' ')
				spaceNum++;
			i++;
			len++;//长度不包含'\0'
		}
		int newLen = len + 2 * spaceNum;
		int p1 = len;
		int p2 = newLen;
		while (p1 >= 0 && p1 <= p2)
		{
			if (str[p1] == ' ')
			{
				str[p2--] = '0';
				str[p2--] = '2';
				str[p2--] = '%';
			}
			else
				str[p2--] = str[p1];
			p1--;
		}
	}
};

int main()
{
	Solution sol;
	string strTmp = "We are happy";
	char* str = new char[24];
	strcpy_s(str, 13, strTmp.c_str());
	sol.repalceSapce(str, 24);
	cout << str << endl;
	system("pause");
	return 0;
}

相关题目

有两个排序的整数数组,分别是数组1和数组2,将数组2合并到数组1中,合并以后的数组1,仍是有序数组。
提示:
数组1有m个元素,数组2有n个元素
可以假设数组1有足够的空间(大于m+n)去容纳从数组2得到的额外的元素。

解题思路

  1. 提示中已经给出,假设array1有足够的空间了,于是我们不需要额外构造一个数组,并且可以从后面不断地比较元素进行合并。
  2. 比较array2与array1中最后面的那个元素,把最大的插入第m+n位
  3. 改变数组的索引,再次进行上面的比较,把最大的元素插入到array1中的第m+n-1位。
  4. 循环一直到结束。循环结束条件:当index1或index2有一个小于0时,此时就可以结束循环了。如果index2小于0,说明目的达到了。如果index1小于0,就把array2中剩下的前面的元素都复制到array1中去就行。

实现代码

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

class Solution {
public:
	void MergeTweArray(int a[], int b[], int aLen, int bLen);
};

int main()
{
	Solution sol;
	int a[10] = { 2,3,8,9,0,0,0,0,0,0 };//o为额外多出来的空间
	int b[4] = { 3,6,7,10 };
	int aLen = 4;
	int bLen = sizeof(b) / sizeof(b[0]);
	sol.MergeTweArray(a, b, 4, 4);
	for (int i = 0; i < (aLen + bLen); i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;
	system("pause");
	return 0;
}

void Solution::MergeTweArray(int a[], int b[], int aLen, int bLen)
{
	int len = aLen + bLen;
	int aPos = aLen - 1;
	int bPos = bLen - 1;
	int pos = len - 1;//合并后的数组索引位置
	while (aPos >= 0 && bPos >= 0)//从后往前比较
	{
		if (b[bPos] > a[aPos])
		{
			a[pos] = b[bPos];
			bPos--;
		}
		else
		{
			a[pos] = a[aPos];
			aPos--;
		}
		pos--;
	}

	if (aPos <= 0)//a数组先用完,b有剩余
	{
		while (bPos >= 0)
		{
			a[pos] = b[bPos];
			bPos--;
		}
	}
	else//b数组用完,a有剩余
	{
		while (aPos >= 0)
		{
			a[pos] = a[aPos];
			aPos--;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/vict_wang/article/details/85305695