剑指5:替换空格

传送门

nowcoder
leetcode

题目描述

请实现一个函数,将一个字符串中的每个空格替换成 %20。
例如,当字符串为 We Are Happy,经过替换之后的字符串为 We%20Are%20Happy。

C++ 代码 - nowcoder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
首先统计出长度,然后从后向前替换。

时间复杂度:O(n)
*/
class Solution {
public:
string replaceSpace(string str) {
int length = str.size();
int spaceCount = 0;
for (int i = 0; i < length; i ++) {
if (str[i] == ' ') spaceCount ++;
}

int newLength = length + spaceCount * 2;
str.resize(newLength);
for (int i = length - 1; i >= 0 && newLength != i; i --) {
// i = newLen,说明前面已经没有空格了
if (str[i] != ' ') str[--newLength] = str[i];
else {
str[--newLength] = '0';
str[--newLength] = '2';
str[--newLength] = '%';
}
}
return str;
}
};

C++ 代码 - leetcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
string replaceSpace(string s) {
int length = s.size(), spaceCount = 0;
for (int i = 0; i < length; i++) {
if (s[i] == ' ') spaceCount++;
}

int newLength = length + spaceCount * 2;
s.resize(newLength);
for (int i = length - 1; i >= 0 && newLength != i; i--) {
// i = newLen,说明前面已经没有空格了
if (s[i] != ' ') s[--newLength] = s[i];
else {
s[--newLength] = '0';
s[--newLength] = '2';
s[--newLength] = '%';
}
}
return s;
}
};

剑指5:替换空格
https://lcf163.github.io/2021/01/29/剑指5:替换空格/
作者
乘风的小站
发布于
2021年1月29日
许可协议