LeetcodeはOffer05を指しています。スペースを置き換えます

暴力的な解決策:

class Solution {
    
    
public:
    string replaceSpace(string s) {
    
    
        for(int i = 0; i < s.length(); i ++){
    
    
            char ch = s[i];
            if(ch == ' '){
    
    
                s.append("  ");
                
                
                for(int j = s.length();  j> i+2; j --){
    
    
                    s[j-1] = s[j - 3]; 
                }
                s[i] = '%';
                s[i+1] = '2';
                s[i + 2] = '0';
            }
        }
        
        return s;

    }
};

時間計算量o(n ^ 2)空間計算量o(1)

気が変わる

class Solution {
    
    
public:
    string replaceSpace(string s) {
    
    
        string str;
        
        for(char &c : s){
    
    
            
            if(c == ' '){
    
    
                str.push_back('%');
                str.push_back('2');
                str.push_back('0');
                
            }
            else {
    
    
                str.push_back(c);
            }

        }
    return str;
    

    
    }
    
};

時間計算量o(n)、空間計算量o(n)

おすすめ

転載: blog.csdn.net/weixin_43579015/article/details/123322394