Backspace
Backspace

Reputation: 302

Replacing duplicates in a string

I am trying to write a code to replace duplicates in string by '*' . The code I have written is-

#include<iostream>
#include<math.h>
#include<string>
using namespace std;


int main()
{
  string ch;
  cin>>ch;
  for(int i=0;i<ch.length()&& (ch[i]!='*');i++)
  {
      for(int j=i+1;j<ch.length()&&ch[j]!='*';j++)   
      {
        if(ch[i]==ch[j])ch[j]='*';
      }
  }
    cout<<ch;
}

The above code gives unexpected results for some inputs. For e.g. if the input is "adad" the answer I get is "ad*d", whereas the output for "adda", and "aadd" matches the expected output. Can anyone tell me what I'm doing wrong ?

Upvotes: 0

Views: 112

Answers (3)

Ashwani
Ashwani

Reputation: 2052

Problem with your code is:

You are stopping outer loop if you encounter *. Now, suppose input is abcabc. In first iteration of outer loop you will change it to abc*bc. In second Iteration of outer loop inner loop will encounter * and will exit (without changing b to *). Same thing will happen to third iteration of outer loop. In fourth iteration of outer loop exit condition (ch[i] != '*') will become false and your program will exit. Here is a fix:

#include<iostream>
#include<math.h>
#include<string>
using namespace std;
int main()
{
    string ch;
    cin >> ch;
    for(int i=0; i < ch.length(); i++)
    {
        for(int j = i + 1; j < ch.length(); j++)     
        {
            if(ch[i] == ch[j] && ch[i] != '*')
                ch[j]='*';
        }
    }
    cout << ch << endl;
}

Upvotes: 0

f1zz0_13
f1zz0_13

Reputation: 495

Hint: Your for loop will break as soon as the loop condition returns false. adad changes to ad*d after the first iteration of the outer for loop. But then i gets set to 1, j is set to 2. Will your second for loop execute with these values?

Upvotes: 0

tnull
tnull

Reputation: 758

Like Piotr S. said in the comments, you need to keep processing the string, even if the current character is *. Here is my take, this should work:

#include<iostream>
#include<math.h>
#include<string>
using namespace std;


int main()
{
    string ch;
    cin >> ch;
    for(int i = 0; i < ch.length(); ++i)
    {
        if(ch[i] == '*') continue; // skip this entry
        for(int j = i + 1; j < ch.length(); ++j)   
        {
            if(ch[i] == ch[j]) ch[j]='*';
        }
    }
    cout<<ch;
}

Upvotes: 2

Related Questions