Removing Consecutive Duplicate Characters in Strings
Fri Mar 08 2024
removeConsecutive:
This function iteratively scans the string, removing duplicates as they appear
removeConsecutiveRecursive:
This function uses recursion for the same purpose, resetting or advancing the index based on duplicate detection
1let str = 'aabb'
2let str1 = 'aaabb'
3let str2 = 'aabaa'
4
5//Iterative
6function removeConsecutive(str){
7    let i = 0
8    while(i < str.length-1){
9        if(str[i] === str[i+1]){
10           str = str.substring(0, i) + str.substring(i + 1)
11           i=0
12        }else{
13            i++
14        }
15    }
16    return str;
17}
18
19//Recurssive
20function removeConsecutiveRecursive(str,i = 0){
21    if(i === str.length -1){
22        return str
23    }
24    if(str[i] === str[i+1]){
25        return removeConsecutiveRecursive(str.substring(0, i) + str.substring(i + 1), 0)
26    }
27    return removeConsecutiveRecursive(str, i + 1);
28}
29
30
31console.log(removeConsecutive(str))
32console.log(removeConsecutive(str1))
33console.log(removeConsecutive(str2))
34
35
36console.log(removeConsecutiveRecursive(str))
37console.log(removeConsecutiveRecursive(str1))
38console.log(removeConsecutiveRecursive(str2))
39
40