Article Directory
1. Topic
URLify. Write a method that replaces all spaces in a string with %20
. It is assumed that there is enough space at the end of the string to hold the new characters, and that the "true" length of the string is known. (Note: For Java
implementation, please use character arrays to operate directly on the array.)
Click here to jump to the topic .
Example 1:
Input: "Mr John Smith ", 13
Output: "Mr%20John%20Smith"
Example 2:
Input: " ", 5
output: "%20%20%20%20%20"
hint:
- The string length is in the range [0, 500000].
2. C# solution
At first, I thought of double-pointer post-order traversal, but I found that the topic is not kind, and the length of the given string S
will have extra spaces, so I have to cut off part of the character array and convert it into a string:
public class Solution {
// 后序遍历
public string ReplaceSpaces(string S, int length) {
int i = length - 1, j = S.Length - 1; // 双指针 i、j
char[] ch = S.ToArray();
while (i >= 0) {
// 后序遍历
if (S[i] == ' ') {
// 如果是空格,后退 3 格改为 "%20"
ch[j--] = '0';
ch[j--] = '2';
ch[j--] = '%';
}
else {
ch[j--] = S[i]; // 不是空格,则复制字符
}
i--;
}
return new string(ch, j + 1, S.Length - j - 1); // 取数组中局部字符转字符串
}
}
- Time complexity: O ( n ) O(n)O ( n )。
- Space Complexity: O ( n ) O(n)O ( n )。
Since it is necessary to convert a local array to a string, there is no need for post-order traversal, just pre-order traversal.
By the way, to be more precise, first traverse the array to record the exact length of the string, and then directly convert the entire array to a string.
Of course, one more traversal may be unnecessary, personal preference.
public class Solution {
// 前序遍历
public string ReplaceSpaces(string S, int length) {
int i = 0, j = 0; // 双指针 i、j
int len = length; // 记录最终字符串长度
for (int k = 0; k < length; k++) {
if (S[k] == ' ') len += 2; // 遇见空格,长度 + 2
}
char[] ch = new char[len];
while (i < length) {
if (S[i] == ' ') {
// 如果是空格,前进 3 格改为 "%20"
ch[j++] = '%';
ch[j++] = '2';
ch[j++] = '0';
}
else {
ch[j++] = S[i]; // 不是空格,则复制字符
}
i++;
}
return new string(ch); // 字符数组转字符串
}
}
- Time complexity: O ( n ) O(n)O ( n )。
- Space Complexity: O ( n ) O(n)O ( n )。