Run-length encoding (compression) · 行程长度编码(压缩)
Squeezing repeated data
- Compression makes data smaller. Run-length encoding (RLE) is one simple way.
- It works well when the same value repeats many times in a row.
- It is lossless: from the squeezed form you can rebuild the exact original.
压缩重复的数据
- 压缩让数据变小。行程长度编码(RLE)是一种简单的方法。
- 当同一个值连续重复很多次时,它的效果很好。
- 它是无损的:从压缩后的形式可以重建出一模一样的原始数据。
What a "run" is
- A run is a stretch of the same character repeated: in
"aaabbc","aaa"is a run of 3. - RLE replaces each run with the character followed by how many times it repeats.
- So
"aaabbc"becomes"a3b2c1"— much shorter when runs are long.
什么是“行程”
- 一个行程是同一个字符连续重复的一段:在
"aaabbc"里,"aaa"是一个长度为 3 的行程。 - RLE 把每个行程替换成那个字符,后面跟上它重复了多少次。
- 所以
"aaabbc"变成"a3b2c1"—— 行程越长,缩得越短。
Counting a run
- To measure a run, look at a character, then count how many of the same character follow it.
- Stop when the next character is different, or you reach the end (
'\0'). - That count is the run's length.
数一个行程
- 要量一个行程,看一个字符,然后数后面跟着多少个相同的字符。
- 当下一个字符不同、或到了末尾(
'\0')时停止。 - 这个计数就是行程的长度。
Building the encoded string
- Walk the input. For each run, write the character, then its count, into the output.
- Move your input position past the whole run before starting the next one.
- End the output string with
'\0'so it is a proper C string.
构建编码后的字符串
- 遍历输入。对每个行程,把字符、再把它的次数写进输出。
- 在开始下一个行程之前,把输入位置移到整个行程之后。
- 用
'\0'结束输出字符串,让它成为一个合格的 C 字符串。
#include <stdio.h>
int main(void) {
const char *s = "aaab";
int i = 0;
char c = s[i];
int count = 0;
while (s[i] == c) { // count the first run
count++;
i++;
}
printf("%c%d\n", c, count); // a3
return 0;
}
Common mistakes
- Run-length encoding stores a value then its count; it only helps when there are long runs.
- It is lossless — the original is restored exactly.
常见错误
- 行程编码先存值再存数量;只有存在长游程时才有用。
- 它是无损的——能精确还原原始数据。
Now you try
- Find each run, then write the character and its count to the output.
- The caller gives you an output buffer big enough to hold the result. Do not write a
main.
现在轮到你了
- 找出每个行程,然后把字符和它的次数写进输出。
- 调用者会给你一个足够大的输出缓冲区来放结果。不要写
main。
Run-length encoding · 游程编码
Replace a run of repeats with count + symbol — lossless. · 把一串重复换成次数 + 符号——无损。
Complete int run_length_at(const char *s, int i) so it returns how many times the character s[i] repeats starting at index i. Do not · 不 write a main. · 完成 int run_length_at(const char *s, int i),让它返回字符 s[i] 从下标 i 开始连续重复了多少次。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete void rle_encode(const char *in, char *out) so it writes the run-length encoding of in into · 生成 out: each run becomes the character then its count. "aaabbc" becomes "a3b2c1". End out with '\0'. Do not · 不 write a main. · 完成 void rle_encode(const char *in, char *out),把 in 的行程长度编码写进 out:每个行程变成“字符 + 次数”。"aaabbc" 变成 "a3b2c1"。用 '\0' 结束 out。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。