剑指 Offer 05 替换空格

标签: 剑指 Offer 发布于:2021-11-23 11:42:46 编辑于:2021-11-24 21:32:07 浏览量:991

概述

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;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/