面试题4_替换空格
//面试题4
//实现一个函数,将字符串中的每个空格都转换成"%20"。
//例如:"we are happy."
//转换之后是:"we20%are20%happy."
//直观思路:从前至后,依次扫描字符串中的每个字符,遇到空格时就将其替换为"20%",直到字符串结尾标识符'\0'。
//时间复杂度是:O(n平方)
//进阶思路:从后至前,使用两个指针,依次扫描字符串中的每个字符,遇到空格时就将其替换为"20%",直到两个指针相等。
//时间复杂度是:O(n)
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
class Solutions
{
public:
void ReplaceBlank(char str[], int length) //length:代表字符数组的总长度
{
if(str==nullptr || length<=0) //输入的字符串是空,或者字符串长度是0
return;
int OriginalLen=0;
int NumOfBlank=0;
int i=0;
while(str[i] != '\0')
{
++OriginalLen;
if(str[i] == ' ')
++NumOfBlank;
++i;
}
int NewLen=0;
NewLen=OriginalLen+NumOfBlank*2;
if(NewLen>length) //字符数组溢出
return;
//cout<<OriginalLen<<","<<NumOfBlank<<","<<NewLen<<endl;
//设置两个指针
int p1=OriginalLen; //指向旧数组的末尾
int p2=NewLen; //指向新数组的末尾
while(p2 != p1)
{
if(str[p1] == ' ')
{
str[p2--]='0';
str[p2--]='2';
str[p2--]='%';
--p1;
}
else
{
str[p2]=str[p1];
--p1;
--p2;
}
}
}
};
int main(void)
{
const int SIZE=50;
char str[SIZE]="we are happy.";
//char str[SIZE]=" wearehappy.";
//char str[SIZE]="wearehappy. ";
//char str[SIZE]="wearehappy.";
//char str[SIZE]="";
cout<<str<<endl;
Solutions object;
object.ReplaceBlank(str,SIZE);
cout<<str<<endl;
system("pause");
return 0;
}