Lexicographically smallest string possible by inserting given character | Java program to implement the above approach ; Function to obtain lexicographically smallest String possible by inserting character c in the String s ; Traverse the String ; If the current character is greater than the given character ; Insert the character before the greater character ; Return the String ; Append the character at the end ; Return the String ; Driver Code
import java . util . * ; class GFG { static String SmallestString ( String s , char c ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) > c ) { String temp = s ; s = s . substring ( 0 , i ) ; s += c ; s += temp . substring ( i , temp . length ( ) ) ; return s ; } } s += c ; return s ; } public static void main ( String args [ ] ) { String S = " acd " ; char C = ' b ' ; System . out . println ( SmallestString ( S , C ) ) ; } }