Check if given String can be split only into subsequences ABC | C ++ program for the above approach ; Function to check if the given string can be splitted into subsequences " ABC " ; Stores the length of the string ; Stores the indices of ' A ' ; Stores the indices of ' B ' ; Stores the indices of ' C ' ; Traverse the string S ; If S [ i ] is equal to ' A ' ; Push the index i in A ; Else if S [ i ] is equal to ' B ' ; Push the index i in B ; Else if S [ i ] is equal to ' C ' ; Push the index i in C ; If N is not multiple of 3 or count of characters ' A ' , ' B ' and ' C ' are not equal ; Return " No " ; Iterate over the deque B ; If A is not empty and B [ i ] is greater than A [ 0 ] ; Removes the front element of A ; Else return " No " ; Iterate over the deque B in reverse ; If C is not empty and last element of C is greater thab B [ i ] ; Removes the last element of C ; Else return " No " ; If none of the above cases satisfy return "Yes' ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string check ( string S ) { int N = S . length ( ) ; deque < int > A ; deque < int > B ; deque < int > C ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' A ' ) { A . push_back ( i ) ; } else if ( S [ i ] == ' B ' ) { B . push_back ( i ) ; } else { C . push_back ( i ) ; } } if ( N % 3 || A . size ( ) != B . size ( ) || A . size ( ) != C . size ( ) ) { return " No " ; } for ( int i = 0 ; i < B . size ( ) ; i ++ ) { if ( ! A . empty ( ) && B [ i ] > A [ 0 ] ) { A . pop_front ( ) ; } else { return " No " ; } } for ( int i = B . size ( ) - 1 ; i >= 0 ; i -- ) { if ( ! C . empty ( ) && B [ i ] < C . back ( ) ) { C . pop_back ( ) ; } else { return " No " ; } } return " Yes " ; } int main ( ) { string S = " ABABCC " ; cout << check ( S ) << endl ; return 0 ; }