Minimum letters to be removed to make all occurrences of a given letter continuous | C ++ implementation of the above approach ; Function to find the minimum number of deletions required to make the occurrences of the given character K continuous ; Find the first occurrence of the given letter ; Iterate from the first occurrence till the end of the sequence ; Find the index from where the occurrence of the character is not continuous ; Update the answer with the number of elements between non - consecutive occurrences of the given letter ; Update the count for all letters which are not equal to the given letter ; Return the count ; Driver code ; Calling the function ; Calling the function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int noOfDeletions ( string str , char k ) { int ans = 0 , cnt = 0 , pos = 0 ; while ( pos < str . length ( ) && str [ pos ] != k ) { pos ++ ; } int i = pos ; while ( i < str . length ( ) ) { while ( i < str . length ( ) && str [ i ] == k ) { i = i + 1 ; } ans = ans + cnt ; cnt = 0 ; while ( i < str . length ( ) && str [ i ] != k ) { i = i + 1 ; cnt = cnt + 1 ; } } return ans ; } int main ( ) { string str1 = " ababababa " ; char k1 = ' a ' ; cout << noOfDeletions ( str1 , k1 ) << endl ; string str2 = " kprkkoinkopt " ; char k2 = ' k ' ; cout << noOfDeletions ( str2 , k2 ) << endl ; }