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 ""

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂


Leave a Reply

avatar
  Subscribe  
Notify of