算法面试字符串-题目2-删除和复制

删除一个字符串所有的a,并且复制所有的b。注:字符数组足够大


如何把字符串的空格变成”%20”?同样,字符数组足够大!



程序如下:

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


class Solution {
public:
//删除一个字符串所有的a,并且复制所有的b。
    char* stringRepaceAndCopy(char A[]) {
       int lenA = strlen(A) ;
       //先删除a,可以利用原来字符串的空间
       //记录b有多少个
       int n = 0,numb = 0;
       for(int i = 0;i < lenA;++i)
       {
		   if(A[i] == 'b')  numb++;
		   //删除a
		   if(A[i] != 'a')  A[n++] = A[i];
		}
		A[n] = 0;//舍去后面的
		int newLength = n + numb; 
		A[newLength] = 0;
		int j = newLength - 1;
		for(int i = n - 1; i >= 0; --i)
		{
			A[j--] = A[i];
			if(A[i] == 'b')   A[j--] = 'b';
		}
		return A;
    }
    //将字符串的空格变成“%20”
	char* changeSpace(char A[])
	{
		int lenA = strlen(A) ;
		int numSpace = 0;
		for(int i = 0;i < lenA; ++i)
		{
			if(A[i] == ' ')  numSpace++;
		}
		cout << numSpace << endl;
		if(numSpace == 0)  return A;
		int newLength = lenA + numSpace * 2;
		cout << "newLength:" << newLength << endl;
		int j = newLength - 1;
		A[newLength] = 0;
		for(int i = lenA - 1; i >= 0;--i)
		{
			if(A[i] == ' ')
			{
				A[j--] = '0';
				A[j--] = '2';
				A[j--] = '%';
			}
			else
				A[j--] = A[i];
		}
		return A;
	}
};


int main()
{
	Solution* p = new Solution;
	char B[100] = "bcdbe f";
	//p->changeSpace(B);
	cout <<p->changeSpace(B)<< endl;
	delete p;
	return 0;
}
    原文作者:Chen-Lee
    原文地址: https://blog.csdn.net/qq_16583687/article/details/75911807
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞