剑指 Offer 05 替换空格

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

标签:剑指 Offer发布于:编辑于:浏览量:1770

概述

https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

直接法

相比于每见到一个字符就添加到 res 里,这里是积攒一段后再添加。

O(n) 的时间复杂度。

class Solution {
public:
    string replaceSpace(string s) {
        string res = "";
        string trg = "%20";
        int start = 0;
        for (int i=0;i<s.size();i++) {
            if (s[i] == ' ') {
                res += s.substr(start, i-start);
                res += trg;
                start = i + 1;
            }
        }
        res += s.substr(start, s.size()-start);
        return res;
    }
};