空格替换
1 #include <iostream> 2 #include <stdlib.h> 3 using namespace std; 4 5 void f(char *s) 6 { 7 char *p=s; 8 while(*s!='\0') 9 { 10 if(*s==' ') 11 { 12 while(*p!='\0') 13 p++; 14 while(p>s) 15 { 16 *(p+2)=*p; 17 p--; 18 } 19 *p='%'; 20 *(p+1)='2'; 21 *(p+2)='0'; 22 } 23 else 24 { 25 s++; 26 } 27 } 28 } 29 30 int main() 31 { 32 char s[100]="hello world"; 33 f(s); 34 cout<<s<<endl; 35 return 0; 36 }
时间复杂度:每个空格移动O(n),n个空格O(n*n)
1 void f(char *s) 2 { 3 int n=strlen(s);//这个n不算'\0',即s[n]='\0' 4 int counts=0;//记录空格总数 5 while(*s!='\0') 6 { 7 if(*s==' ') 8 counts++; 9 s++; 10 } 11 int n2=n+2*counts; 12 char *p1,*p2; 13 p1=s+n; 14 p2=s+n2; 15 while(p1<p2) 16 { 17 if(*p1!=' ') 18 { 19 *p2=*p1; 20 p1--; 21 p2--; 22 } 23 else 24 { 25 *(p2-2)='%'; 26 *(p2-1)='2'; 27 *(p2)='0'; 28 p1--; 29 p2-=3; 30 } 31 } 32 }
每个元素最多移动一次,时间复杂度O(n)
posted on 2014-03-13 10:21 crane_practice 阅读(170) 评论(0) 编辑 收藏 举报