Remove adjacent duplicates
Given a string, recursively remove adjacent duplicate characters from string. The output string should not have any adjacent duplicates.Input:
geeeksforgeek
Output:
gksforgk
Check my geeksforgeeks submission: http://www.practice.geeksforgeeks.org/viewSol.php?subId=1579026&pid=1583
Answer: (Solution using both loops & recursion is present)
#include <stdio.h>
#include <string.h>
void duplicate_removal(char *s)
{
static char *p, *q;
static char flag = 0;
if(flag == 1) {
if(*p != *s) {
q = s;
flag = 2;
return;
}
duplicate_removal(++s);
s = p;
}
if((flag == 2) && (*q == '\0')) {
*s = '\0';
flag = 0;
return;
}
if(flag == 2) {
*s = *q++;
}
if(*s == '\0') {
flag = 0;
return;
}
else if ((flag == 0) && (*s == *(s+1))) {
p = s;
flag = 1;
duplicate_removal(s);
s = p;
}
duplicate_removal(++s);
}
int main(void) {
char buff[32];
#if 0
int i,j,k,l,len;
#endif
printf("String: ");
scanf("%s",buff);
#if 0
len = strlen(buff);
for(i=0; i
if(buff[i] == buff[i+1]) {
for(k=i; k
if(buff[i] != buff[k]) {
j = k;
break;
}
}
for(k=j,l=i; k
buff[l] = buff[k];
}
buff[l] = '\0';
}
len = strlen(buff);
}
#endif
duplicate_removal(buff);
printf("Output: %s\n",buff);
return 0;
}
No comments:
Post a Comment