Problem solving with programming: Couple elimination problem
Given a string of some symbols, write a program to transform a string by repeatedly eliminating two same symbols occurring together.
For example if the input string is 'RGGB' it will be reduced to 'RB' because 'GG' can be eliminated.
Here are some more examples of input - output
Input | Output
-------------------
GBRRBR | GR
BGRGRR | BGRG
Given a string of some symbols, write a program to transform a string by repeatedly eliminating two same symbols occurring together.
For example if the input string is 'RGGB' it will be reduced to 'RB' because 'GG' can be eliminated.
Here are some more examples of input - output
Input | Output
-------------------
GBRRBR | GR
BGRGRR | BGRG
char string[MAX]; char temp[MAX]; cin>>string; int i; int tempInd = 0; //to track temp string for( i = 0 ; string[i] != '\0' ; i++) { //If temp string has atleast one character if( tempInd > 0) { //If previous, and current chars are same, erase if( temp[tempInd-1] == string[i] ) { tempInd--; } else//not same, append the char to temp { temp[tempInd++] = string[i]; } } else //temp is empty, simply append the character { temp[tempInd++] = string[i]; } } //append the NULL character at the end temp[tempInd] = '\0'; //print the transformed string cout<<temp<<endl;http://tech-queries.blogspot.com/2011/02/remove-pairs.html
- void remove_pair(char* input)
- {
- int len = strlen(input);
- int i, j = 0;
- for (i=1; i <= len; i++)
- {
- //Cancel pairs
- while ((input[i] == input[j]) && (j >= 0))
- {
- i++;
- j--;
- }
- input[++j] = input[i]; // if ++j ==i, don't copy
- }
- return;
- }