Please implement a function to replace each space in the string s with "%20".
Example 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
limit:
0 <= length of s <= 10000
In-situ modification
In the C++ language, string is designed to be a "variable" type (reference material), so it can be modified in place without creating a new string.
Since spaces need to be replaced with "%20", the total number of characters in the string increases, so the length of the original string s needs to be extended. The calculation formula is: new string length = original string length + 2 * number of spaces, example As shown below.
class Solution {
public:
string replaceSpace(string s) {
int count = 0, len = s.size();
// 统计空格数量
for (char c : s) {
if (c == ' ') count++;
}
// 修改 s 长度
s.resize(len + 2 * count);//2 * count 因为原有空格已经有了一个位置,因此乘以2就够了
// 倒序遍历修改
for(int i = len - 1, j = s.size() - 1; i < j; i--, j--) {
//当 i = j 时跳出(代表左方已没有空格,无需继续遍历),最左侧的字母无须再赋值
//因此,用i < j;
if (s[i] != ' ')
s[j] = s[i];
else {
s[j - 2] = '%';
s[j - 1] = '2';
s[j] = '0';
j -= 2;//左移两个位置
}
}
return s;
}
};
Complexity analysis:
Time complexity O(N): Both traversal statistics and traversal modification use O(N) time.
Space complexity O(1): Since the length of s is extended in situ, O(1) extra space is used.
Author: jyd
link: https: //leetcode-cn.com/problems/ti-huan-kong-ge-lcof/solution/mian-shi-ti-05-ti-huan-kong-ge-ji-jian-qing -xi-tu-/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.