LeetCode 剑指 Offer 05. 替换空格

题目描述

🔥 剑指 Offer 05. 替换空格

给定一个字符串,逐个替换字符串中的空格为 %20。请注意,返回的字符串应该是一个新的字符串,原字符串不变。

示例 1: 输入:s = "We are happy." 输出:"We%20are%20happy."

示例 2: 输入:s = " Hello World! " 输出:"Hello%20World!"

提示:

  • 0 <= s.length <= 10000

image-20241107204051393

思路分析

思路描述

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
func replaceSpace(s string) string {
	spaceCount := 0
	for _, char := range s {
		if char == ' ' {
			spaceCount++
		}
	}

	newLength := len(s) + spaceCount*2
	result := make([]byte, newLength)
	index := newLength - 1

	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == ' ' {
			result[index] = '0'
			result[index-1] = '2'
			result[index-2] = '%'
			index -= 3
		} else {
			result[index] = s[i]
			index--
		}
	}

	return string(result)
}
1
write your code here

🍏 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2024/86567750
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!