您的位置:首页 > 其它

请实现一个函数,把字符串中的每个空格替换成“%20”。

2016-05-02 13:47 411 查看
第一种:
思路:
遍历一个字符串,遇到空格向后移动三个char空间,插入%20,直到遍历结束。
时间复杂度O(n^2)
空间复杂度O(1)
#include<iostream>
#include<stdlib.h>
#include<assert.h>
using namespace std;
void memmove(void* src,void* des,size_t size)
{
char* d=(char*)des;
char* s=(char*)src;
if((s-d>0)&&(s-d< size))
{
while(size--)
{
s[size-1]=d[size-1];
}
}
else
{
int i=0;
while(i<size)
{
s[i]=d[i];
i++;
}
}
}
void Replace(char* s)
{
assert(s);
while(*s)
{
if(*s!=' ')
{
s++;
}
else
{
memmove(s+3,s+1,strlen(s+1)+1);
*s++='%';
*s++='2';
*s='0';
}
}

}
int main()
{
char s[30]="we are  young";
Replace(s);
cout<<s<<endl;
system("pause");
return 0;
}
结果:




第二种:
思路:如果面试官允许开辟新的空间,则利用两个指针*s,*str分别指向原字符串,新字符串的首部,
依次遍历原字符串,字符不是空格,就将*s赋值给*str,如果遇到空格,向新字符串中插入%20,直到原字符串遍历结束。
时间复杂度O(n)
空间复杂度O(n)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void Replace(char* s,char* str)
{
while(*s)
{
if(*s!=' ')
{
*str=*s;
str++;

}
else
{
strcpy(str,"%20");
str=str+3;

}
s++;
}
*str='\0';
}
int main()
{
char s[]="we are young";
char str[30];
Replace(s,str);
printf("%s\n",str);
system("pause");
return 0;
}

第三种:
思路:
先遍历一遍字符数组,计算空格数量,定义两个指针p1,p2,一个指向原字符串的末尾,一个变化后的字符串末尾,p1从尾向头遍历,依次把值赋给p2,p1遇到空格时,在p2所指向的位置插入“%20”。
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
void Insert(char* str,int len)
{
assert(str);
int newlength=len+1;
int i=0;
while(str[i]!='\0')
{
if(str[i]==' ')
{
newlength+=2;
}
i++;
}
char* p1=str+len;
char* p2=str+newlength-1;
while(p1!=str)
{
if(*p1==' ')
{
p2-=2;
strncpy(p2,"%20",sizeof(char)*3);
}
else
{
*p2=*p1;

}
p1--;
p2--;

}
}
int main()
{
char s[30]="we are young";
Insert(s,strlen(s));
printf("%s\n",s);
system("pause");
return 0;
}


本文出自 “liveyoung” 博客,转载请与作者联系!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: