Lexicographically smaller string by swapping at most one character pair | Java program check whether is it possible to make String A lexicographically smaller than String B ; Swap function ; Function that finds whether is it possible to make String A lexicographically smaller than String B ; Condition if String A is already smaller than B ; Sorting temp String ; Condition for first changed character of String A and temp ; Condition if String A is already sorted ; Finding first changed character from last of String A ; Swap the two characters ; Condition if String A is smaller than B ; Driver Code
import java . util . * ; class GFG { static String swap ( String str , int i , int j ) { char [ ] tempArr = str . toCharArray ( ) ; char temp = tempArr [ i ] ; tempArr [ i ] = tempArr [ j ] ; tempArr [ j ] = temp ; return String . valueOf ( tempArr ) ; } static boolean IsLexicographicallySmaller ( String A , String B ) { if ( A . compareTo ( B ) < 0 ) { return true ; } String temp = A ; char p [ ] = temp . toCharArray ( ) ; Arrays . sort ( p ) ; temp = String . valueOf ( p ) ; int index = - 1 ; for ( int i = 0 ; i < A . length ( ) ; i ++ ) { if ( A . charAt ( i ) != temp . charAt ( i ) ) { index = i ; break ; } } if ( index == - 1 ) { return false ; } int j = 0 ; for ( int i = 0 ; i < A . length ( ) ; i ++ ) { if ( A . charAt ( i ) == temp . charAt ( index ) ) j = i ; } A = swap ( A , index , j ) ; if ( A . compareTo ( B ) < 0 ) { return true ; } else { return false ; } } public static void main ( String args [ ] ) { String A = " AGAIN " ; String B = " ACTION " ; if ( IsLexicographicallySmaller ( A , B ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }