Inplace remove all occurrences of ‘AB’ and ‘C’ from the string

Given a string, inplace remove all occurrences of “AB” and “C” from it.


 

For example,

Input string = 'CBAABCAB'

String after removal of 'AB' and 'C' is 'BA'
'CBAABCAB' -> 'C BA AB C AB' -> 'BA'

 

Input string = 'ABACB'

String after removal of 'AB' and 'C' is ''
'ABACB' -> 'AB A C B' -> 'AB' -> ''

 

Input string = 'ABCACBCAABB'

String after removal of 'AB' and 'C' is ''
'ABCACBCAABB' -> 'AB C C C AB B' -> 'AB AB' -> ''

 
The main challenge lies in the in-place doing the conversion in one traversal of the string. The problem demands removal of all adjacent as well as non-adjacent occurrences of string AB. i.e. for a string for a given string say ADAABCB, after removing first adjacent occurrence of AB (and C of-course), we get ADAB which again needs to be processed for adjacent AB (no C this time (why?)). Therefore, the final output string will be AD.

 
Below is C implementation of the idea –

 

Download   Run Code

Output:

String after removal of "AB" and "C" is ""

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of