/*
字符串替换:
1.一个换一个
函数将字符串中的字符’‘移到字符串的前部分,前面的非’’
字符后移,但不能改变非’‘字符的先后顺序,函数返回串中非’'字符的数量。(要求尽可能的占用少的时间和辅助空间)。
例如:原始串为autoch**ips,处理后为******autochips,函数返回9.
*/
#include<stdio.h>
#include<vector>
#include<string.h>
#include<string>
#include<iostream>
using namespace std;
int CheckString(char *str)
{
int i = 0;
int count = 0;
int j;
while(str[i] != '\0')
{
if(str[i] != '*')
count++;
i++;
}
while( i >= 0)
{
if(str[i] == '*')
{
j = i;
while(j > 0 && str[j] == '*')
{
j--;
}
swap(str[j],str[i]);
}
i--;
}
cout << count << endl;
return count;
}
int main()
{
char str[100] = "abc**de**de**a*asd";
int len = sizeof(str)/sizeof(str[0]);
CheckString(str);
cout << str << endl;
return 0;
}
2.一个换多个(插入)
将空格替换成%20,见<剑指offer>例题4
时间复杂度为O(n),空间复杂度为O(1)
void replaceSpace(char *str,int length)
{
if(str != NULL && length <= 0)
return ;
int i=0;
int oldnumber=0;//记录以前的长度
int replacenumber=0;//记录空格的数量
while(str[i] != '\0')
{
oldnumber++;
if(str[i]==' ')
{
replacenumber++;
}
i++;
}
int newlength=oldnumber+replacenumber*2;//插入后的长度
if(newlength>length)//如果计算后的长度大于总长度就无法插入
return ;
int pOldlength=oldnumber; //注意不要减一因为隐藏个‘\0’也要算里
int pNewlength=newlength;
while(pOldlength>=0&&pNewlength>pOldlength)//放字符
{
if(str[pOldlength]==' ') //碰到空格就替换
{
str[pNewlength--]='0';
str[pNewlength--]='2';
str[pNewlength--]='%';
}
else //不是空格就把pOldlength指向的字符装入pNewlength指向的位置
{
str[pNewlength--]=str[pOldlength];
}
pOldlength--; //不管是if还是elsr都要把pOldlength前移
}
}
int main()
{
char str[100] ="a b c d e";
int len = sizeof(str)/sizeof(str[0]);
replaceSpace(str,len);
cout << str << endl;
return 0;
}
3.多个换一个(删除)
将字符串中连续的空格删除,只保留一个空格"a b c d"->“a b c d”
时间复杂度为O(n),空间复杂度为O(1)
void replaceSpace(string &str,int length)
{
int i = 0;
if(length <= 1)
return;
while(str[i] != '\0')
{
int j = i + 1;
if(str[i] == ' ' && str[j] == ' ')
{
while(str[j] != '\0' && str[j] == ' ')
{
j++;
}
swap(str[i + 1],str[j]);
}
++i;
}
}
int main()
{
string str = "a b c d";
replaceSpace(str,str.size());
cout << str << endl;
return 0;
}