1. 题目描述
请实现一个函数,把字符串 s 中的每个空格替换成”%20”。
示例 1
输入:s = "We are happy."输出:"We%20are%20happy."
2. 题目分析
这个题目思路比较清晰,遍历字符串,当遇到空格,就将%20加入新字符串,其他情况,直接将旧的加入
3. 代码实现
func replaceSpace(s string) string {res := []byte{}for i := 0; i < len(s); i++ {if s[i] == ' ' {res = append(res, []byte("%20")...)} else {res = append(res, s[i])}}return string(res)}
4. 复杂度分析
- 时间复杂度:O(n)
- 空间复杂度:O(n)
