题目
请实现一个函数,把字符串 s
中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy." 输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 要把空格换成%20 这样字符串的长度必然会增加
// 所以先计算出最终长度
class Solution {
public:
string replaceSpace(string s) {
int count = 0; //计算总共有多少个空格
int oldSize = s.size();
for (int i = 0; i < s.size(); ++i)
{
if (s[i] == ' ')
{
count++;
}
}
s.resize(s.size() + count * 2);
for (int i = s.size() - 1, j = oldSize - 1; i >= 0; --i, --j)
{
if (s[j] == ' ')
{
s[i] = '0';
s[i - 1] = '2';
s[i - 2] = '%';
i -= 2; //for循环自减1,这里只需要减2
}
else
{
s[i] = s[j];
}
}
return s;
}
};