替換空格

時間限制:1秒 空間限制:32768K 熱度指數:938460
本題知識點:  字符串

 算法知識視頻講解算法

題目描述

請實現一個函數,將一個字符串中的每一個空格替換成「%20」。例如,當字符串爲We Are Happy.則通過替換以後的字符串爲We%20Are%20Happy。
 
解題思路有兩個:
  1. 從前向後替換,這樣的話每找到一個空格,都會將空格後的全部字符向後移動2個距離,這樣的話計算量比較大,算法的複雜性大,我本身就使用的這種方法。並且,因爲好久沒有練習算法題,因此一開始直接str[i] = "%20",忘記一個字符不能用字符串來替代。
  2. class Solution {
    public:
        void replaceSpace(char *str,int length) {
            
            for(int i = 0; i < length-1;){
                if(str[i] == ' '){
                    for(int j = length - 1; j > i; j--){
                        str[j+2] = str[j];
                    }
                 str[i] = '%';
                 str[i+1] = '2';
                 str[i+2] = '0';
                 i = i + 3;
                    
                }
                else{
                    i++;
                }
    
            }
    
        }
    };

     

  3. 標準的簡單方法是,全部的字符只須要移動一次便可。即首先從前向後記錄一下空格的個數。而後從後向前進行空格的替換,這樣的話就能夠每一個字符只移動一次,與第一種方法相比下降了計算複雜度。
    連接:https://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423
    來源:牛客網
    
    class Solution {
    public:
        void replaceSpace(char *str,int length) {
            int count=0;
            for(int i=0;i<length;i++){
                if(str[i]==' ')
                    count++;
            }
            for(int i=length-1;i>=0;i--){
                if(str[i]!=' '){
                    str[i+2*count]=str[i];
                }
                else{
                    count--;
                    str[i+2*count]='%';
                    str[i+2*count+1]='2';
                    str[i+2*count+2]='0';
                }
            }
        }
    };