剑指 Offer 05. 替换空格-两种解法:1,用strings.Replace-2,遍历添加

替换空格

http://www.nowcoder.com/questionTerminal/0e26e5551f2b489b9f58bc83aa4b6c68

题解

该题难度为简单。

解法一:使用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提交的代码
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务