Minimum removals required such that given string consists only of a pair of alternating characters | C ++ program for the above approach ; Function to find the maximum length of alternating occurrences of a pair of characters in a string s ; Stores the next character for alternating sequence ; Stores the length of alternating occurrences of a pair of characters ; Traverse the given string ; If current character is same as the required character ; Increase length by 1 ; Reset required character ; Return the length ; Function to find minimum characters required to be deleted from S to obtain an alternating sequence ; Stores maximum length of alternating sequence of two characters ; Stores length of the string ; Generate every pair of English alphabets ; Function call to find length of alternating sequence for current pair of characters ; Update len to store the maximum of len and newLen in len ; Return n - len as the final result ; Driver Code ; Given Input ; Function call to find minimum characters required to be removed from S to make it an alternating sequence of a pair of characters
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLength ( string s , char i , char j ) { char required = i ; int length = 0 ; for ( char curr : s ) { if ( curr == required ) { length += 1 ; if ( required == i ) required = j ; else required = i ; } } return length ; } int minimumDeletions ( string S ) { int len = 0 ; int n = S . length ( ) ; for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { for ( char j = i + 1 ; j <= ' z ' ; j ++ ) { int newLen = findLength ( S , i , j ) ; len = max ( len , newLen ) ; } } return n - len ; } int main ( ) { string S = " adebbeeaebd " ; cout << minimumDeletions ( S ) ; return 0 ; }