剑指 Offer 05. 替换空格

题目描述

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

示例 1:

1
2
输入:s = "We are happy."
输出:"We%20are%20happy."

限制:

$0 <= s 的长度 <= 10000$


算法

(模拟) $O(n)$

创建一个答案字符串 $res$,遍历原字符串,如果是空格则加 $%20$,否则加当前字符。

时间复杂度

$O(n)$

空间复杂度

$O(n)$

C++ 代码

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
string replaceSpace(string s) {
string res;
for (auto c : s)
if (c == ' ') res += "%20";
else res += c;
return res;
}
};
Author: tonngw
Link: https://tonngw.com/2022/07/08/剑指 Offer/剑指 Offer 05. 替换空格/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.