Write a function that accepts a string argument and removes duplicate characters that are neighbors. If the new string also has duplicate neighbors, those should be removed also.
reduce_dups('abb') => "a"
reduce_dups('abba') => ""
reduce_dups('aba') => "aba"
We can solve this problem by for
looping through the string starting at index 1. Then compare the current character str[i]
, to the previous character prev
.
When we find a set of duplicate touching characters (str[i] === prev)
, we can concat all the characters before the dups, and all the characters after the dups, creating a new string.
Finally, we reset our variables: str
, i
, prev
. This allows our program to run a new loop, on our newly created string, repeating the steps above.
function remove_dups(str) {
let prev = str[0];
for (let i = 1; i < str.length; i++) {
if (str[i] === prev) {
str = str.slice(0, i - 1) + str.slice(i + 1, str.length);
prev = str[0];
i = 0;
} else {
prev = str[i];
}
}
return str;
}
remove_dups('abba') // ''
remove_dups('aab') // 'b'
remove_dups('aba') // 'aba'