String compression
Run-length encode in place: count each run of identical characters, then write the character followed by its count.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
read scans forward through one run of identical characters at a time while write places the compressed result. A run of length 1 is written as just the character; a longer run is written as the character followed by its count as digits.
Code
public static int Compress(char[] chars) {
int read = 0, write = 0;
while (read < chars.Length) {
char c = chars[read];
int start = read;
while (read < chars.Length && chars[read] == c) read++;
chars[write++] = c;
int count = read - start;
if (count > 1)
foreach (char d in count.ToString())
chars[write++] = d;
}
return write;
}static int compress(char[] chars) {
int read = 0, write = 0;
while (read < chars.length) {
char c = chars[read];
int start = read;
while (read < chars.length && chars[read] == c) read++;
chars[write++] = c;
int count = read - start;
if (count > 1)
for (char d : String.valueOf(count).toCharArray())
chars[write++] = d;
}
return write;
}int compress(vector<char>& chars) {
int read = 0, write = 0;
while (read < (int)chars.size()) {
char c = chars[read];
int start = read;
while (read < (int)chars.size() && chars[read] == c) read++;
chars[write++] = c;
int count = read - start;
if (count > 1)
for (char d : to_string(count))
chars[write++] = d;
}
return write;
}def compress(chars: list[str]) -> int:
read = write = 0
while read < len(chars):
c = chars[read]
start = read
while read < len(chars) and chars[read] == c: read += 1
chars[write] = c; write += 1
count = read - start
if count > 1:
for d in str(count):
chars[write] = d; write += 1
return writeTips
- Writing happens at the write pointer, which only moves forward, so the compression works in place without extra space.
- A run can have a count of 10 or more, which is why the count is written one digit at a time.
In the .NET library
This differs from the longest-run counting seen elsewhere: here every run is written out, not just tracked for a maximum.