Skip to content

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:

  1. 0 <= S.length <= 500000

Solutions

Solution 1: Using replace() function

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
class Solution:
    def replaceSpaces(self, S: str, length: int) -> str:
        return S[:length].replace(' ', '%20')
1
2
3
function replaceSpaces(S: string, length: number): string {
    return S.slice(0, length).replace(/\s/g, '%20');
}
1
2
3
4
5
impl Solution {
    pub fn replace_spaces(s: String, length: i32) -> String {
        s[..length as usize].replace(' ', "%20")
    }
}
1
2
3
4
5
6
7
8
/**
 * @param {string} S
 * @param {number} length
 * @return {string}
 */
var replaceSpaces = function (S, length) {
    return encodeURI(S.substring(0,