Check if given string can be formed by two other strings or their permutations | Java implementation of the approach ; Function to sort the given string using counting sort ; Array to store the count of each character ; Insert characters in the string in increasing order ; Function that returns true if str can be generated from any permutation of the two strings selected from the given vector ; Sort the given string ; Select two strings at a time from given vector ; Get the concatenated string ; Sort the resultant string ; If the resultant string is equal to the given string str ; No valid pair found ; Driver code
import java . util . * ; class GFG { static int MAX = 26 ; static String countingsort ( char [ ] s ) { int [ ] count = new int [ MAX ] ; for ( int i = 0 ; i < s . length ; i ++ ) { count [ s [ i ] - ' a ' ] ++ ; } int index = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { int j = 0 ; while ( j < count [ i ] ) { s [ index ++ ] = ( char ) ( i + ' a ' ) ; j ++ ; } } return String . valueOf ( s ) ; } static boolean isPossible ( Vector < String > v , String str ) { str = countingsort ( str . toCharArray ( ) ) ; for ( int i = 0 ; i < v . size ( ) - 1 ; i ++ ) { for ( int j = i + 1 ; j < v . size ( ) ; j ++ ) { String temp = v . get ( i ) + v . get ( j ) ; temp = countingsort ( temp . toCharArray ( ) ) ; if ( temp . equals ( str ) ) { return true ; } } } return false ; } public static void main ( String [ ] args ) { String str = " amazon " ; String [ ] arr = { " fds " , " oxq " , " zoa " , " epw " , " amn " } ; Vector < String > v = new Vector < String > ( Arrays . asList ( arr ) ) ; if ( isPossible ( v , str ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }