The task is to compress repeating letters with count number given a string.
The boilerplate code:
function compress(str) {
// your code here
}
If it's not a string, return ""
if(!str) return "";
Start from the beginning of the string, and look at each character one by one. Keep a counter that tracks how many times the current character repeats consecutively.
let result = "";
let count = 1;
If the next character is the same as the current one, increase the counter
for(let i=1; i <= str.length; i++) {
if(str[i] === str[i - 1] {
count++
}
}
If the next character is different, the current group has ended. So add the character to the result, then add the count only if it is repeated more than once
else {
result += str[i - 1];
if(count > 1) result += count
count = 1;
}
The final code
function compress(str) {
// your code here
if(!str) return "";
let result = "";
let count = 1;
for(let i=1; i <= str.length; i++) {
if(str[i] === str[i-1]) {
count++
} else {
result += str[i - 1];
if(count > 1) result += count
count = 1;
}
}
return result;
That's all folks!
Top comments (0)