Run-length string compression
Medium TimeO(n) SpaceO(n)
Given a string s, return it with each run of identical consecutive characters replaced by that character followed by the length of the run, so "aaabccddddd" becomes "a3b1c2d5". A run of one still carries its count, so "b" becomes "b1". Only consecutive characters form a run. Because this can make a string longer, the original is returned whenever the encoded form is not shorter.
Examples
Example 1
- Input
- s = "aaabccddddd"
- Output
- Runs of 3, 1, 2 and 5 become
"a3b1c2d5"a3,b1,c2andd5— 8 characters against the 11 they replace.
Example 2
- Input
- s = "abc"
- Output
- Three runs of one encode to
"abc""a1b1c1", which is longer than"abc", so the original is returned.
The Code
function compress(s) {
let out = "";
let i = 0;
while (i < s.length) {
const ch = s[i];
let run = 0;
while (i < s.length && s[i] === ch) {
run++;
i++;
}
out += ch + run;
}
return out.length < s.length ? out : s;
}
compress("aaabccddddd");Done
The first 19 calls, of 21. This one does not fit on a page.
More like this
All strings examples (13) →- Reverse words Split on whitespace, walk backwards, join again.
- Valid anagram Count letters up with one word, down with the other.
- Common prefix Start with the whole first word, shrink until everything matches.
- First unique char Count every character first, then find the earliest with count 1.
- Longest unique substring A sliding window that jumps forward past any repeat.
- Caesar cipher Rotate each letter through the alphabet and wrap around.