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