Largest substring of str2 which is a prefix of str1 | C ++ 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
#include <iostream> NEW_LINE using namespace std ; string findPrefix ( string str1 , string str2 ) { int pos = -1 ; while ( ! str1 . empty ( ) ) { if ( str2 . find ( str1 ) == string :: npos ) str1 . pop_back ( ) ; else { pos = str2 . find ( str1 ) ; break ; } } if ( pos == -1 ) return " - 1" ; return str1 ; } int main ( ) { string str1 = " geeksfor " ; string str2 = " forgeeks " ; cout << findPrefix ( str1 , str2 ) ; return 0 ; }