JavaScript Algorithm: Alternating Characters

For today’s algorithm, we are going to write a function called alternatingCharacters
that will take one string, s
as input.
You are given a string that only contains characters A
and B
. The goal of the function is to change the string so that the characters alternate and there are no matching adjacent characters. The function will return the number of matching adjacent character deletions it will take to have an A
and B
alternate-only string. Let’s look at an example:
let s = "ABAABBAB";
In our input string above there are some repeat adjacent characters. We will highlight the characters that we can remove to have an alternating string.
"ABAABBAB" --> remove A at position 3 and B at position 5
We remove the two characters so that we can have a string that doesn’t contain matching adjacent characters. The function will return 2
.
Let’s turn this into code:
let deleteCount = 0;
Our deleteCount
variable will hold the number of matching adjacent character deletions.
for(let i = 0; i < s.length; i++){
if(s[i] === s[i+1]){
deleteCount++;
}
}
Next, we iterate through the characters in our input string. We use the if-statement to check if the current character matches the character next to it in the string. If they match, the current character is unneeded so we increment the deleteCount
variable.
After the loop ends, we return the deleteCount
variable.
return deleteCount;
That’s the end of our short function. Here is the rest of the code:
function alternatingCharacters(s) {
let deleteCount = 0; for(let i = 0; i < s.length; i++){
if(s[i] === s[i+1]){
deleteCount++;
}
}
return deleteCount;
}
If you found this algorithm helpful, check out my other recent JavaScript algorithm solutions: