text: Lexicographically largest string possible by reversing substrings having even number of 1 s | Java program for the above approach ; Function to find the lexicographically maximum string by reversing substrings having even numbers of 1 s ; Store size of string ; Traverse the string ; Count the number of 1 s ; Stores the starting index ; Stores the end index ; Increment count , when 1 is encountered ; Traverse the remaining string ; Reverse the string from starting and end index ; Printing the string ; Driver Code
code: import java . util . * ; class GFG { static void lexicographicallyMax ( String s ) { int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; int beg = i ; int end = i ; if ( s . charAt ( i ) == '1' ) count ++ ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( s . charAt ( j ) == '1' ) count ++ ; if ( count % 2 == 0 && count != 0 ) { end = j ; break ; } } s = reverse ( s , beg , end + 1 ) ; } System . out . println ( s ) ; } static String reverse ( String s , int beg , int end ) { StringBuilder x = new StringBuilder ( " " ) ; for ( int i = 0 ; i < beg ; i ++ ) x . append ( s . charAt ( i ) ) ; for ( int i = end - 1 ; i >= beg ; i -- ) x . append ( s . charAt ( i ) ) ; for ( int i = end ; i < s . length ( ) ; i ++ ) x . append ( s . charAt ( i ) ) ; return x . toString ( ) ; } public static void main ( String args [ ] ) { String S = "0101" ; lexicographicallyMax ( S ) ; } }