列表

详情


面试题 01.03. URL化

URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)

 

示例 1:

输入:"Mr John Smith    ", 13
输出:"Mr%20John%20Smith"

示例 2:

输入:"               ", 5
输出:"%20%20%20%20%20"

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: string replaceSpaces(string S, int length) { } };

python3 解法, 执行用时: 48 ms, 内存消耗: 22.6 MB, 提交时间: 2023-09-15 11:00:34

class Solution:
    def replaceSpaces(self, S: str, length: int) -> str:
        return S[:length].replace(' ','%20')

rust 解法, 执行用时: 8 ms, 内存消耗: 5.9 MB, 提交时间: 2023-09-15 11:00:24

impl Solution {
    pub fn replace_spaces(s: String, length: i32) -> String {
        let mut r = String::new();
        for (idx, c) in s.char_indices() {
            if idx >= length as usize {
                break;
            }
            if c == ' '{
                r.push_str("%20");
            } else {
                r.push(c);
            }

        }
        r
        
        // 一行的解法
        // s[0..length as usize].replace(" ", "%20")
    }
}

golang 解法, 执行用时: 12 ms, 内存消耗: 8.4 MB, 提交时间: 2023-09-15 10:56:28

import "strings"

func replaceSpaces(S string, length int) string {
	builder := strings.Builder{}
	for i := 0; i < length; i++ {
		if S[i] != ' ' {
			builder.WriteByte(S[i])
		} else {
			builder.WriteString("%20")
		}
	}
	return builder.String()
}

// 直接操作底层的字符数组
func replaceSpaces2(S string, length int) string {
	bytes := []byte(S)
	i, j := len(S)-1, length-1
	for j >= 0 {
		if bytes[j] == ' ' {
			bytes[i] = '0'
			bytes[i-1] = '2'
			bytes[i-2] = '%'
			i -= 3
		} else {
			bytes[i] = bytes[j]
			i--
		}
		j--
	}
	return string(bytes[i+1:])
}

golang 解法, 执行用时: 24 ms, 内存消耗: 11.4 MB, 提交时间: 2023-09-15 10:55:52

func replaceSpaces(S string, length int) string {
    // 双指针逆序
	runeS := []rune(S)
	i := length-1
	j := len(S)-1
	// 逆序遍历, 遇上空格填充%20,否则字符填入
	for i >= 0 {
		if runeS[i] == ' ' {
			runeS[j] = '0'
			runeS[j-1] = '2'
			runeS[j-2] = '%'
			j -= 3
		} else {
			runeS[j] = runeS[i]
			j--
		}
		i--
	}
	// j最后时-1,所以是[0:len(S)]
	return string(runeS[j+1:len(S)])
}

javascript 解法, 执行用时: 112 ms, 内存消耗: 64.1 MB, 提交时间: 2023-09-15 10:55:01

/**
 * @param {string} S
 * @param {number} length
 * @return {string}
 */
var replaceSpaces = function(S, length) {
    return S.slice(0,length).replaceAll(" ", "%20");
};

php 解法, 执行用时: 32 ms, 内存消耗: 20 MB, 提交时间: 2021-05-25 11:48:49

class Solution {

    /**
     * @param String $S
     * @param Integer $length
     * @return String
     */
    function replaceSpaces($S, $length) {
        $S = substr($S, 0, $length);
        return preg_replace('/\s/', '%20', $S);
    }
}

上一题