01.03. String to URL
Description
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters,and that you are given the "true" length of the string. (Note: If implementing in Java,please use a character array so that you can perform this operation in place.)
Example 1:
Input: "Mr John Smith ", 13 Output: "Mr%20John%20Smith" Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8.
Example 2:
Input: " ", 5 Output: "%20%20%20%20%20"
Note:
0 <= S.length <= 500000
Solutions
Solution 1: Using replace() function
Thinking
Spaces in the first \(length\) characters must become %20. \(S\) may contain trailing padding, so a replace on the whole string is wrong.
A library replace finishes the substitution in linear time. Slice \(S[:length]\) first, then replace spaces, which handles both the live prefix and the padding.
That matches the Python code: one slice and one replace, linear in the output length.
Directly use replace to replace all with %20:
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string.
1 2 3 | |
1 2 3 | |
1 2 3 4 5 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Solution 2: Simulation
Thinking
A library helper is not portable across languages that the problem may be solved in.
Scan the valid prefix character by character: write %20 for a space and the original character otherwise. The buffer is at most three times as long, still a linear pass.
Traverse each character \(c\) in the string. When encountering a space, add %20 to the result, otherwise add \(c\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string.
1 2 3 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |