[toc]
leetcode
题目描述
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
通过次数631,642提交次数837,529
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/ti-huan-kong-ge-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
法1
字符串拼接
用原生的字符串拼接,golang支持字符串用+拼接
if s[i] == ' ' {s = s[:i] + "%20" + s[i+1:]}
- 时间复杂度(O(n))
- 空间复杂度(O(1))
执行结果
法1
func replaceSpace(s string) string {
for i := 0; i < len(s); i++ {
if s[i] == ' ' {//查找替换
s = s[:i] + "%20" + s[i+1:]
}
}
return s
}
执行用时:
0 ms
, 在所有 Go 提交中击败了
100.00%
的用户
内存消耗:
2.2 MB
, 在所有 Go 提交中击败了
21.05%
的用户
通过测试用例:
27 / 27
优化
func replaceSpace(s string) string {
for i := 0; i < len(s); i++ {
if s[i] == ' ' {
s = s[:i] + "%20" + s[i+1:]
i+=2//优化部分可以少遍历2个,因为后面两个为20,不为空' '
}
}
return s
}
本文由mdnice多平台发布