LeetCode 443. 压缩字符串

题目描述

🔥 443. 压缩字符串

思路分析

思路描述

参考代码

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
27
28
29
30
31
32
33
34
func compress(chars []byte) int {
	n := len(chars)
	if n <= 1 {
		return n
	}
	index := 0
	count := 1
	for i := 1; i < n; i++ {
		if chars[i] == chars[i-1] {
			count++
		} else {
			chars[index] = chars[i-1]
			index++
			if count > 1 {
				countStr := strconv.Itoa(count)
				for j := 0; j < len(countStr); j++ {
					chars[index] = countStr[j]
					index++
				}
			}
			count = 1
		}
	}
	chars[index] = chars[n-1]
	index++
	if count > 1 {
		countStr := strconv.Itoa(count)
		for j := 0; j < len(countStr); j++ {
			chars[index] = countStr[j]
			index++
		}
	}
	return index
}
1
write your code here

🍏 点击查看 Java 题解

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