Remove adjacent duplicates in a string in C

大憨熊 提交于 2019-12-13 23:07:23

问题


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.



来源:https://stackoverflow.com/questions/20049661/remove-adjacent-duplicates-in-a-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!