forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrle_compression.py
More file actions
76 lines (58 loc) · 1.49 KB
/
rle_compression.py
File metadata and controls
76 lines (58 loc) · 1.49 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
Run-Length Encoding (RLE)
A simple lossless compression algorithm that encodes consecutive repeated
characters as a count followed by the character. Decompression fully recovers
the original data.
Reference: https://en.wikipedia.org/wiki/Run-length_encoding
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
def encode_rle(data: str) -> str:
"""Compress a string using run-length encoding.
Args:
data: The input string to compress.
Returns:
The RLE-encoded string.
Examples:
>>> encode_rle("aaabbc")
'3a2b1c'
>>> encode_rle("")
''
"""
if not data:
return ""
encoded: str = ""
prev_char: str = ""
count: int = 1
for char in data:
if char != prev_char:
if prev_char:
encoded += str(count) + prev_char
count = 1
prev_char = char
else:
count += 1
return encoded + str(count) + prev_char
def decode_rle(data: str) -> str:
"""Decompress a run-length encoded string.
Args:
data: The RLE-encoded string.
Returns:
The decoded original string.
Examples:
>>> decode_rle("3a2b1c")
'aaabbc'
>>> decode_rle("")
''
"""
decoded: str = ""
count: str = ""
for char in data:
if not char.isdigit():
decoded += char * int(count)
count = ""
else:
count += char
return decoded