一、《剑指OFFER》面试题4 替换空格
实现函数将字符串的每个空格替换成“%20”.例如“we are happy”则输出"we%20are%20happy"
第一个想到就是新建一个字符串数组,然后遇到空格就在新数组添加%20
这样实现的空间复杂度比较大。
第二种是书上提供的时间复杂度为O(N2)的思想。每遇到一个空格,就将空格之后的字符逐一推后两个字符。复杂度为O(N2)
第三种是书上提供的复杂度为O(n)的思想。
1.先遍历字符串,找出空格的个数
2.延长字符串的长度,使新字符串的长度为原字符串的长度+两倍的空格字符数
3.两个字符指针分别指向新旧字符串的最右字符,向左遍历。
4.如果原字符指针遇到不是空格,则新字符指针则复制字符,否则,在新字符指针填写%20.
5.重复4直到字符串开头。
#include "stdio.h"
#include <string>
#include<iostream>
#define Max 100
using namespace std;
char str[Max];
void input(){
cout<<"please input a string:";
cin.getline(str,100);
}
void replaceBlank(char *str){
int length=0;
int Blank =0;
while (str[length]!='\0')
{
++length;
if (str[length]== ' ')
{
++Blank;
}
}
int lenafter;
lenafter = length + 2 * Blank;
int a,b;
a=length;
b=lenafter;
while (a>=0 && b>a)
{
if (str[a]!=' ')
{
str[b] = str[a];
b--;
}
else{
str[b--] = '0';
str[b--] = '2';
str[b--] = '%';
}
a--;
}
}
void output(char* string){
cout<<string<<endl;
}
void main(){
input();
replaceBlank(str);
output(str);
}
自己写的代码,健壮性不好,要加强
代码路径E:\代码库\vc\ReplaceBlank