Skip to content

Commit 3e8d7ce

Browse files
committed
Add 1.6 String Compression solution
1 parent a47c77e commit 3e8d7ce

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/* Implement a method to perform basic string
2+
compression using the counts of repeated characters
3+
Ex: 'aabcccccaaa' would become a2b1c5a3
4+
*/
5+
6+
const stringCompression = (str) => {
7+
if (!str.length) {
8+
return '';
9+
}
10+
var compStr = '';
11+
var count = 1;
12+
var currentChar = str[0];
13+
for (let i = 1; i < str.length; i++) {
14+
let char = str[i];
15+
if (char === currentChar) {
16+
count++;
17+
if (i === str.length - 1) {
18+
compStr += `${currentChar}${count}`;
19+
}
20+
} else {
21+
compStr += `${currentChar}${count}`;
22+
currentChar = char;
23+
count = 1;
24+
}
25+
}
26+
return compStr;
27+
}
28+
29+
// TESTS
30+
console.log(stringCompression('aabcccccaaa') === 'a2b1c5a3');
31+
console.log(stringCompression('cccccccc') === 'c8');
32+
console.log(stringCompression('') === '');
33+
console.log(stringCompression('AabccCccaaa') === 'A1a1b1c2C1c2a3');

0 commit comments

Comments
 (0)