I recently completed a coding challenge. One of the tasks was to write a string compression algorithm. This is a very popular algorithm, and I will be writing about how to solve it here.
The task:
Given a string of letters, if there are consecutive repeating characters, append the character followed by the number of times it is seen. If the character appears only once, do not include a number.
Ex: compress a string 'aabbcddd', to 'a2b2cd3'
The first steps we'd have to take are:
- Split the string into an array to be able to iterate through it
- Create a new string, which would hold the compressed version
- Create a for loop to iterate through the first string
function compress(string){
let compressed = ""
let stringArray = string.split("")
for (let i = 0; i < stringArray.length; i++){
}
}
Next, we would need to keep track of several things within the for loop:
- The current count of the consecutive letters with each iteration
- The letter that is being counted.
The function will now look like this:
function compress(string){
let compressed = ""
let stringArray = string.split("")
for (let i = 0; i < stringArray.length; i++){
let count = 1
let letter = stringArray[i]
}
}
We will need to create a while loop to compare letters. The loop will have two conditions: 1) if i is less than the length of stringArray -1, 2) if the current letter in the iteration is the same as the neighboring letter
When both conditions are met, both the count and index positions will be incremented
function compress(string){
let compressed = ""
let stringArray = string.split("")
for (let i = 0; i < stringArray.length; i++){
let count = 1
let letter = stringArray[i]
while (i < stringArray.length - 1 && stringArray[i] === stringArray[i + 1] {
count++
i++
}
}
}
For the final part, we want to add the letter and the number of times it appears to the compressed string. Then we want to return the string.
function compress(string){
let compressed = ""
let stringArray = string.split("")
for (let i = 0; i < stringArray.length; i++){
let count = 1
let letter = stringArray[i]
while (i < stringArray.length - 1 && stringArray[i] === stringArray[i + 1] {
count++
i++
}
if (count === 1){
compressed += letter
} else {
compressed =+ letter + count}
}
}
return compressed
}
aaaand done!
Top comments (0)