Wednesday, 10 August 2011

Removing Pair in a string.

Suppose we have a string "RGBBGBGR". we have to eliminate the couple (two same chars adjacent to each other) recursively.
For example
RGBBGBGR --> RGGBGR-->RBGR
This solution is O(n) with recursion.
Program code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void pair_remove(char []);
void main()
{
char a[]="RGBBGBGRRGRR";
clrscr();
pair_remove(a);
printf("%s\n", a);
getch();
}
void pair_remove(char a[])
{
int remove=0,i,j;
int len=strlen(a);
for(i=0;i<len-1;i++){
if( a[i]== a[i+1] )
{
for(j=i+2;j<=len;j++) 
{
a[i]=a[j];
i++;
remove=1;
}
}
if ( remove )
break;
}
if ( remove )
pair_remove(arr);
}

No comments:

Post a Comment