user15337825
user15337825

Reputation:

How to Recursively remove adjacent duplicate characters?

It's output look like: Hello =>Helo

Problem require:

  1. no loop
  2. Except for the originally used string methods (size(), substr(...)), no other methods (for example, find(...), erase(...)) can be used.

I tried several times, but it usually have weird output. And my idea is that it will be made up from the back. Here is my code:

string removeR(string s)
{
    int length = s.size();
    int i=0;
    if (i < length)
    {
        if (s[i] == s[i + 1])
        {
            s[i] = s[i + 1];
            s[i + 1] = s[i + 2];
            return removeR(s.substr(i + 1));
        }
    }
    return s;
}

It's output sometimes is error, sometimes is Original string. I need somebody help to check out thank you!!

Upvotes: 0

Views: 199

Answers (2)

user15337825
user15337825

Reputation:

int pos=0;
string removeR(string s)
{
    int length = s.size();
    if (pos == length - 1)
    {
        pos = 0;
        return s;
    }
    
    if (s[pos] == s[pos + 1])
        s = s.substr(0, pos) + s.substr(pos + 1, length - pos - 1);
    else pos++;
    return removeR(s);
}

Upvotes: 0

Kola73
Kola73

Reputation: 152

Try this

void removeAdj(string& strIn, int pos=0)
{
    int len = strIn.size();
    if (pos == len - 1)
        return;
    if (strIn[pos] == strIn[pos + 1])
        strIn = strIn.substr(0, pos) + strIn.substr(pos+1, len-pos-1);
    else
        pos++;
    removeAdj(strIn, pos);
}

Upvotes: 1

Related Questions