JZ02 替换空格

本文最后更新于:2022年4月9日 中午

image-20211006101753140

Solution

  • 原字符串扩容
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
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* @param s string字符串
* @return string字符串
*/
string replaceSpace(string s) {
// write code here
int count = 0; // 空格个数
int oldSize = s.size();
for (char c : s) {
if (c == ' ') count++;
}

s.resize(oldSize + 2 * count);
int newSize = s.size();
for (int i = oldSize-1; i >= 0; --i) {
if (s[i] != ' ') s[--newSize] = s[i];
else {
s[--newSize] = '0';
s[--newSize] = '2';
s[--newSize] = '%';
}
}
return s;
}
};
  • 定义新字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string replaceSpace(string s) {
// write code here
string ss;
for (int i = 0; i < s.size(); ++i) {
if (s[i] != ' ') {
ss += s[i];
} else {
ss += "%20";
}
}
return ss;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!