Home > front end >  Remove adjacent duplicates
Remove adjacent duplicates

Time:01-10

Expected output is "ca" but I'm getting "aca". I have dry ran it, but do not understood why it is doing so. Please, can anyone help me in solving this?

#include<bits/stdc  .h>
using namespace std;
    
int main()
{
    string a = "abbaca";
    int i = 0;
    while(i < a.size()){
        if(a[i] == a[i 1]){
            a.erase(i, i 1);
            i = 0;
        }
        else{
            i  ;
        }
    }
    cout << a;
    
    return 0;
}

CodePudding user response:

a.erase(i, i 1) is wrong.

The string::erase() method takes a starting index and a count, not a pair of indexes denoting a range, as you are thinking.

When removing the duplicate bs, i is 1, and you erase i 1=2 chars, thus "abbaca" becomes "aaca", which is correct. But then, the loop starts over, and when removing the duplicate as, i is 0, so you erase i 1=1 char, thus "aaca" becomes "aca", which is wrong.

You want to remove exact 2 chars each time, so use a.erase(i, 2) instead.

Online Demo

CodePudding user response:

The function 'erase()' erases a part of the string content, shortening the length of the string.The second parameter in the erase function is the count, it means how many characters you want it to remove. If you want 'ca' as expected output you should mention 2 as count of characters to be removed. In the first case it becomes 2 so bb is removed but for 'aa' the count becomes as 1 so 'aca' is the output.

Below is the code for output 'ca', change this erase statement as shown:

    if(a[i]==a[i 1]){
        a.erase(i,2);
        i=0;
    }

keep the rest as same

  •  Tags:  
  • Related