Remove adjacent duplicates in a string in C

2019-09-25 15:57发布

问题:

How to remove all adjacent duplicates in a string in C. say for example..if "caaabbcdd" is the given string then it should remove sequentially as

 1. cbbcdd

 2. ccdd

 3. dd

thus an empty string is returned in the end. Time complexity can be O(n^2) for starting.Can anyone help.

so far this i what i have done

void recursiven2(char *str)
{
int i,j,k,len;
    len=strlen(str);
    for(i=0;i<len-1;i++)
    {
    if(str[i]==str[i+1])
    {
        for(j=i;j<len-2;j++)
            str[j]=str[j+2];
        str[j]='\0';
    }
    }

}

回答1:

You can refer to this. It has a very nice explanation.



回答2:

Your code is close, but not quite.

It's easier to think about this in terms of "if this character is the same as the previous, drop it". Your code is more like "if this character is the same as the next", if you see the difference.

Also, memmove() just loves this.

Perhaps something like:

void compress(char *str)
{
  size_t len = strlen(str);

  if(len <= 1)
    return;

  for(size_t i = 1; i < len; )
  {
    if(str[i] == str[i - 1])
    {
      memmove(&str[i], &str[i + 1], (len - (i + 1) + 1);
      --len;
    }
    else
      ++i;
  }
}

There might be an obi-wan error (or two!) in the above, I haven't tested it.



标签: c c-strings