Make the string lexicographically smallest and non palindromic by replacing exactly one character | Java program to make the string lexicographically smallest non palindromic string by replacing exactly one character ; Function to find the required string ; length of the string ; Iterate till half of the string ; replacing a non ' a ' char with ' a ' ; Check if there is no ' a ' in string we replace last char of string by ' b ' ; If the input is a single character ; Driver code
import java . util . * ; class GFG { static String findStr ( String S ) { StringBuilder sb = new StringBuilder ( S ) ; int n = sb . length ( ) ; for ( int i = 0 ; i < n / 2 ; ++ i ) { if ( sb . charAt ( i ) != ' a ' ) { sb . setCharAt ( i , ' a ' ) ; return sb . toString ( ) ; } } sb . setCharAt ( n - 1 , ' b ' ) ; return n < 2 ? " ▁ - 1 ▁ " : sb . toString ( ) ; } public static void main ( String [ ] args ) { String str = " a " ; System . out . println ( findStr ( str ) ) ; String str1 = " abccba " ; System . out . println ( findStr ( str1 ) ) ; } }