Check if a Binary String can be sorted in decreasing order by removing non | Java program for the above approach ; Function to sort the given string in decreasing order by removing the non adjacent characters ; Keeps the track whether the string can be sorted or not ; Traverse the given string S ; Check if S [ i ] and S [ i + 1 ] are both '1' ; Traverse the string S from the indices i to 0 ; If S [ j ] and S [ j + 1 ] is equal to 0 ; Mark flag false ; If flag is 0 , then it is not possible to sort the string ; Otherwise ; Driver Code
import java . util . * ; class GFG { static String canSortString ( String S , int N ) { int flag = 1 ; int i , j ; for ( i = N - 2 ; i >= 0 ; i -- ) { if ( S . charAt ( i ) == '1' && S . charAt ( i + 1 ) == '1' ) { break ; } } for ( j = i ; j >= 0 ; j -- ) { if ( S . charAt ( j ) == '0' && S . charAt ( j + 1 ) == '0' ) { flag = 0 ; break ; } } if ( flag == 0 ) { return " No " ; } else { return " Yes " ; } } public static void main ( String [ ] args ) { String S = "10101011011" ; int N = S . length ( ) ; System . out . println ( canSortString ( S , N ) ) ; } }