Check if given String can be split only into subsequences ABC | Java 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 curr B 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
import java . io . * ; import java . util . * ; class GFG { public static String check ( String S ) { int N = S . length ( ) ; Deque < Integer > A = new LinkedList < Integer > ( ) ; Deque < Integer > B = new LinkedList < Integer > ( ) ; Deque < Integer > C = new LinkedList < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( S . charAt ( i ) == ' A ' ) { A . addLast ( i ) ; } else if ( S . charAt ( i ) == ' B ' ) { B . addLast ( i ) ; } else { C . addLast ( i ) ; } } if ( N % 3 > 0 || A . size ( ) != B . size ( ) || A . size ( ) != C . size ( ) ) { return " No " ; } for ( Iterator itr = B . iterator ( ) ; itr . hasNext ( ) ; ) { Integer b = ( Integer ) itr . next ( ) ; if ( A . size ( ) > 0 && b > A . getFirst ( ) ) { A . pop ( ) ; } else { return " No " ; } } for ( Iterator itr = B . descendingIterator ( ) ; itr . hasNext ( ) ; ) { Integer b = ( Integer ) itr . next ( ) ; if ( C . size ( ) > 0 && b < C . getLast ( ) ) { C . pollLast ( ) ; } else { return " No " ; } } return " Yes " ; } public static void main ( String [ ] args ) { String S = " ABABCC " ; System . out . println ( check ( S ) ) ; } }