leetcode string replace spaces

THE

problem

Insert picture description here

solution

Code



/* 
思路:  先查找空格, 确定替换后的大小。 对于有下表的数据, 一定要先考虑从末尾开始向前遍历。 
不过这个是new 的string , 也不用从末尾开始。

-   find ' ' , and get all length;
-  while(i>0)
- -  end pointer --; instead '';
- - 
- 
*/

class Solution {
    
    
public:
   /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    *
    * 
    * @param s string字符串 
    * @return string字符串
    */
   string replaceSpace(string s) {
    
    
       // write code here
       int maxnums = 0, spacenums = 0;

       maxnums = s.size()+2*spacenums;
       string temp ;
       for(int i = 0 ;i<s.size();i++){
    
    
           if(s[i]==' '){
    
    
               spacenums++;
               temp.append("%20");             
           }
           else {
    
    
               temp = temp+s[i]; 
           }
           
       }     
       return temp;
       
   }
};

Summary and reflection

  1. If you create a new array, you don't need to traverse from the end. If you start from itself, you have to start from the end.

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114179995