Pop string from left to right if matches in JavaScript

Viewed 181

If you see two consecutive characters that are the same, you pop them from left to right, until you cannot pop any more characters. Return the resulting string. let str = "abba"

"abba" - pop the two b's -> "aa"

"aa" - pop the two a's -> ""

return ""

Here's what i have tried so far:

function match(str){
    
 for (let i = 0; i< str.length; i++){
   if (str[i] === str[i+1]){
     return str.replace(str[i], ""); 
   
    } 
  }
};
match('abba');

It removes one b only. On first loop, i want it to remove two b's and console the output. On second i want the remaining two a's to remove and console the output. Also It would be great if good time complexity is maintained.

1 Answers

Use recursion.

function match(str){
    if(str.length==1 || str=="") {
        return str;
    }
    for (let i = 0; i< str.length-1; i++) {
        if(str[i] === str[i+1] && i+2==str.length) {
            return str.substr(0,i);
        } else if(i+2==str.length) {
            return str;
        } else if (str[i] === str[i+1]) {
            return match(str.substr(0,i)+str.substr(i+2,(str.length)-(i+2))); 
        }
    }
};

console.log('aa = '+ match('aa'));
console.log('abba = '+ match('abba'));
console.log('abccba = '+ match('abccba'));
console.log('abdccba = '+ match('abdccba'));
console.log('aabdccba = '+ match('aabdccba'));
console.log('abdccbaa = '+ match('abdccbaa'));
console.log('abbac = '+ match('abbac'));
console.log('abbcc = '+ match('abbcc'));

Related