Solution of String to URL LCCI

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

Ideas of solving a problem

This question mainly focuses on the knowledge of substitution in go language. The problem is to replace all the space strings with 20%. And there is enough space at the end of the string for the new characters to know the length of the string. So we can set the length read in S to be the maximum length set. Here’s a little bit about the replace method.Strings.Replace(s, old, new, -1), s is the string, old is the string to be replaced, new is the string to be replaced.-1 represents the replacement of all old strings, and if n>0 returns a new string that replaces the first n nonoverlapping old substrings in s with new. This code is O (n) in time complexity and O (n) in space complexity. Memory consumption is 8Mb.

Code

package main

import (
	"fmt"
	"strings"
)
func main(){
	input := "     "
	fmt.Println(replaceSpaces(input,5))
}
func replaceSpaces(S string, length int) string {

	return strings.Replace(S[:length]," ","%20",-1)
}


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-to-url-lcci

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值