替换空格

自己费了九牛二虎之力,看过答案,过了很久后 写的代码:

 1 class Solution {
 2 public:
 3     void replaceSpace(char *str,int length) {
 4         int num0 = 0;
 5         for(int i =0 ;i< length ;i++){
 6             if(str[i]== ' '){
 7                 num0++;
 8             }
 9         }
10         int num = 2 * num0; //这里一开始忘了,导致溢出,后来又乘以3 更加不对了
11         int j = 0;
12         for (int i = 0 ;i<length ;i++){
13             
14             if(str[length -i -1] != ' '){
15                 str[length+num-1-j] = str[length -1-i];
16                 j++;
17             }
18             else{
19                 str[length +num -1-j] ='0';
20                 j++;
21                 str[length +num -1-j] ='2';
22                 j++;
23                 str[length +num -1-j] ='%';
24                 j++;
25                     
26             }
27         }
28     }
29 };

榜首答案:虽然思想一样,但是人家的特别干练,且变量的赋值很讲究。

 1 class Solution {
 2 public:
 3     void replaceSpace(char *str,int length) {
 4          if(str==NULL)
 5              return ;
 6          int CountOfBlanks=0;
 7          int Originallength=0;
 8          for(int i=0;str[i]!='';i++)
 9              {
10              Originallength++;
11              if(str[i]==' ')
12                  ++CountOfBlanks;
13          }
14          int len =Originallength+2*CountOfBlanks;
15          if(len+1>length)
16              return ;
17           
18          char*pStr1=str+Originallength;//复制结束符‘’
19          char*pStr2=str+len;
20         while(pStr1<pStr2) // 这个指针用的很巧妙
21             {
22             if(*pStr1==' ')
23                 {
24                 *pStr2--='0';
25                 *pStr2--='2';
26                 *pStr2--='%';    
27             }
28             else
29              {
30                  *pStr2--=*pStr1;
31             }
32             --pStr1;
33         }
34     }
35 };

这件事告诉我们。有时候倒着做就可以了,题目一种思路 倒着进行

发现用python 简直无敌啊。像学习c的,思维都比较死板 按部就班,但是python就不一样了,很是活跃啊

1 # -*- coding:utf-8 -*-
2 class Solution:
3     # s 源字符串
4     def replaceSpace(self, s):
5         # write code here
6         s = s.replace(' ','%20')
7         return s

这里的

s.replace(' ','%20') 必须等于一个值,要不然没变化






原文地址:https://www.cnblogs.com/xiaochige/p/8066747.html