题解

该题难度为简单。

解法一:使用strings.Replace

//Go
func replaceSpace(s string) string {
    return strings.Replace(s, " ", "%20", -1)
}

解法二:遍历添加

//Go
func replaceSpace(s string) string {
    ans := ""
    for _,v := range s{
        if v == ' '{
            ans = ans + "%20"
        } else {
            ans = ans + string(v)
        }
    }
    return ans
}

leetcode-执行:

执行用时:
0 ms, 在所有 Go 提交中击败了100.00%的用户
内存消耗:
3.4 MB, 在所有 Go 提交中击败了16.95%的用户

牛客网执行:

运行时间:2ms
超过100.00%用Go提交的代码
占用内存:956KB
超过23.81%用Go提交的代码