#remove adjacent duplicates

6 messages · Page 1 of 1 (latest)

obsidian jacinth
#

Me and my classmate completed this exercise in two different ways,

Is there a simpler way to complete this task that is more rookie-friendly?
The reason I'm asking is because this is one of the exercises that we should dig into and really understand before our examination.

The automated judge didn't approve my first solution, using a function of my own creation, (this works for all testcases that I tried):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void compress(char *str);

int main()
{
    char str[60];
    while(scanf("%59s", str)==1){
    compress(str);
    printf("%s\n", str);
 
    return 0;
}
}

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;
  }
}

The automated judge approved my second solution, doing it all inside main function, even though it didn't work for all testcases that I tried. :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char s[60];
    char *ptr;
    int d;
    int str_len;
    int ptr_len;

    while(scanf("%59s", s)==1)
    {
        
        str_len = strlen(s);

        for (int i = 0; i < str_len; i++)
            if (s[i] == s[i+1])
            d = d + 1;

        ptr_len = str_len - d;

        d = 0;

        ptr = malloc (ptr_len * sizeof(char));

        for (int i = 0; i < str_len; i++){
            if (s[i] == s[i+1])
                d = d + 1;
            else
                ptr[i-d] = s[i];
        }

        for (int i = 0; i < ptr_len; i++)
            s[i] = ptr[i];

        s[ptr_len] = '\0';

        printf("%s\n", s);

        d = str_len = ptr_len = 0;
        free(ptr);
    }
}
half flumeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

vast hedge
#

The easiest way to do this in my opinion is to make 2 pointers that point to the string, one read pointer and one write pointer. The loop should update the read pointer on each iteration but not update the write pointer (or write to it) if you wrote a character in the last iteration and the character that the read pointer is pointing to is the same character as was written in the last iteration

gaunt summit
vast hedge
#

ye

half flumeBOT
#

This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.