剑指offer第五题,两个,其实有点不严谨,但思想是这个思想,一个节约空间,另一个好像也没有节约太多的时间(当字符数组长度很大的时候),嗯,就这样
#include<stdio.h>
#include<string.h>
#define SIZE 10
char* replaceSpace(char* s);
char* replaceSpace2(char* s);
int main()
{
char s[] = "We are happy.";
puts(s);
//puts(replaceSpace(s));
puts(replaceSpace2(s));
return 0;
}
char* replaceSpace(char* s){
int count = 0;
int old_length,new_length;
int i,j;
for(i = 0;i < strlen(s);i++)
if(s[i] == ' ')
count++;
old_length = strlen(s);
new_length = count * 2 + old_length;
i = new_length;
j = old_length;
//printf("%d %d %d\n",count,i,j);
while(i >= 0 && j >= 0)
{
if(s[j] != ' ')
s[i--] = s[j--];
else
{
j--;
s[i--] = '0';
s[i--] = '2';
s[i--] = '%';
}
}
return s;
}
char* replaceSpace2(char* s){
char* res = NULL;
int i = 0,j = 0;
res = (char*)calloc(strlen(s) * 3 + 1,sizeof(char));
while(s[j] != '\0')
{
if(s[j] != ' ')
res[i++] = s[j++];
else
{
j++;
res[i++] = '%';
res[i++] = '2';
res[i++] = '0';
}
}
return res;
}