Modify string by inserting characters such that every K | Java Program to implement the above approach ; Function to replace all ' ? ' characters in a string such that the given conditions are satisfied ; Traverse the string to Map the characters with respective positions ; Traverse the string again and replace all unknown characters ; If i % k is not found in the Map M , then return - 1 ; Update S [ i ] ; Print the string S ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static void fillString ( String str , int k ) { char s [ ] = str . toCharArray ( ) ; HashMap < Integer , Character > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] != ' ? ' ) { mp . put ( i % k , s [ i ] ) ; } } for ( int i = 0 ; i < s . length ; i ++ ) { if ( ! mp . containsKey ( i % k ) ) { System . out . println ( - 1 ) ; return ; } s [ i ] = mp . getOrDefault ( i % k , s [ i ] ) ; } System . out . println ( new String ( s ) ) ; } public static void main ( String [ ] args ) { String S = " ? ? ? ? abcd " ; int K = 4 ; fillString ( S , K ) ; } }