Skip to content

Commit 8064f53

Browse files
committed
Implement the 'string compression' algorithm
1 parent 518fa10 commit 8064f53

File tree

4 files changed

+41
-0
lines changed

4 files changed

+41
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ An algorithm is a finite sequence of well-defined, computer-implementable instru
3030
* [Is unique](src/algorithms/string/unique) - check a string for uniqueness;
3131
* [Check permutation](src/algorithms/string/permutation) - check if a string is a permutation of the other;
3232
* [URLify](src/algorithms/string/urlify) - replace all spaces in a string with '%20';
33+
* [String compression](src/algorithms/string/compression) - perform basic string compression using the counts of repeated characters;
3334
* **Sort**
3435
* [Insertion sort](src/algorithms/sort/insertion/simple) - sort an array with a simple insertion algorithm;
3536
* [Merge sort](src/algorithms/sort/merge) - sort an array with a merge sort algorithm;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# String compression
2+
3+
Implement a method to perform basic string compression using the counts of repeated characters.
4+
5+
For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.
6+
7+
You can assume the string has only uppercase and lowercase letters (a - z).
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { compression } from "../compression";
2+
3+
test.each([
4+
["aabcccccaaa", "a2b1c5a3"],
5+
["abcde", "abcde"]
6+
])("the compressed value of the string '%p' is '%p'", (input, output) => {
7+
expect(compression(input)).toBe(output);
8+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* A method to perform basic string compression using the counts of repeated characters.
3+
* - The string aabcccccaaa would become a2blc5a3;
4+
* - If the "compressed" string is not smaller than the original one, the method returns the original string.
5+
* @param {string} input
6+
* @returns string
7+
*/
8+
export function compression(input: string): string {
9+
const len = input.length;
10+
const output = [];
11+
12+
let counter = 1;
13+
for (let i = 0; i < len; i++) {
14+
if (input[i] === input[i + 1]) {
15+
counter++;
16+
} else {
17+
output.push(input[i], counter);
18+
counter = 1;
19+
}
20+
}
21+
22+
const result = output.join("");
23+
24+
return result.length > len ? input : result;
25+
}

0 commit comments

Comments
 (0)