Check whether given string can be generated after concatenating given strings | Java implementation of the approach ; Function that return true if pre is a prefix of str ; While there are characters to match ; If characters differ at any position ; str starts with pre ; Function that return true if suff is a suffix of str ; While there are characters to match ; If characters differ at any position ; str ends with suff ; Function that returns true if str = a + b or str = b + a ; str cannot be generated by concatenating a and b ; If str starts with a i . e . a is a prefix of str ; Check if the rest of the characters are equal to b i . e . b is a suffix of str ; If str starts with b i . e . b is a prefix of str ; Check if the rest of the characters are equal to a i . e . a is a suffix of str ; Driver code
import java . util . * ; class GFG { static boolean startsWith ( String str , String pre ) { int strLen = str . length ( ) ; int preLen = pre . length ( ) ; int i = 0 , j = 0 ; while ( i < strLen && j < preLen ) { if ( str . charAt ( i ) != pre . charAt ( j ) ) return false ; i ++ ; j ++ ; } return true ; } static boolean endsWith ( String str , String suff ) { int i = str . length ( ) - 1 ; int j = suff . length ( ) - 1 ; while ( i >= 0 && j >= 0 ) { if ( str . charAt ( i ) != suff . charAt ( j ) ) return false ; i -- ; j -- ; } return true ; } static boolean checkString ( String str , String a , String b ) { if ( str . length ( ) != a . length ( ) + b . length ( ) ) return false ; if ( startsWith ( str , a ) ) { if ( endsWith ( str , b ) ) return true ; } if ( startsWith ( str , b ) ) { if ( endsWith ( str , a ) ) return true ; } return false ; } public static void main ( String args [ ] ) { String str = " GeeksforGeeks " ; String a = " Geeksfo " ; String b = " rGeeks " ; if ( checkString ( str , a , b ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }