Largest substring of str2 which is a prefix of str1 | Java implementation of the approach ; Function to return the largest substring in str2 which is a prefix of str1 ; To store the index in str2 which matches the prefix in str1 ; While there are characters left in str1 ; If the prefix is not found in str2 ; Remove the last character ; Prefix found ; No substring found in str2 that matches the prefix of str1 ; Driver code
import java . util . * ; class GFG { static String findPrefix ( String str1 , String str2 ) { boolean pos = false ; while ( str1 . length ( ) > 0 ) { if ( ! str2 . contains ( str1 ) ) str1 = str1 . substring ( 0 , str1 . length ( ) - 1 ) ; else { pos = str2 . contains ( str1 ) ; break ; } } if ( pos == false ) return " - 1" ; return str1 ; } public static void main ( String [ ] args ) { String str1 = " geeksfor " ; String str2 = " forgeeks " ; System . out . println ( findPrefix ( str1 , str2 ) ) ; } }