Leetcode75-443-String-Compression

🧠 思路总结

因为要求“You must write an algorithm that uses only constant extra space.”,所以可以考虑使用 双指针 的方法(一个指针进行读取,一个指针进行写入,类似于快慢指针)。用count记录当前字符出现的次数,如果下一个字符与当前不同的话,把当前字符写到chars[write]中。如果count > 1,把count转化成字符串,之后将字符串转化成new character array。最后write就是最终数组的长度。

❗ 易错点 / 小坑

  • 不需要sort,因为是连续字符

✅ 代码(Java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int compress(char[] chars) {
int write = 0;
int read = 0;

while (read < chars.length){
char curr = chars[read];
int count = 0;
while (read < chars.length && chars[read] == curr){
read++;
count++;
}
chars[write] = curr;
write++;
if (count > 1){
for (char c : Integer.toString(count).toCharArray()){
chars[write] = c;
write++;
}
}
}
return write;
}
}

Leetcode75-443-String-Compression
https://powersixxx.github.io/leetcode-blog/2026/01/31/Leetcode75-443-String-Compression/
作者
Baowen Liu
发布于
2026年1月31日
许可协议