Longest string which is prefix string of at least two strings | C ++ program to find longest string which is prefix string of at least two strings ; Function to find Max length of the prefix ; Base case ; Iterating over all the alphabets ; Checking if char exists in current string or not ; If atleast 2 string have that character ; Recursive call to i + 1 ; Driver code ; Initialising strings ; push strings into vectors .
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max1 = 0 ; int MaxLength ( vector < string > v , int i , int m ) { if ( i >= m ) { return m - 1 ; } for ( int k = 0 ; k < 26 ; k ++ ) { char c = ' a ' + k ; vector < string > v1 ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( v [ j ] [ i ] == c ) { v1 . push_back ( v [ j ] ) ; } } if ( v1 . size ( ) >= 2 ) { max1 = max ( max1 , MaxLength ( v1 , i + 1 , m ) ) ; } else { max1 = max ( max1 , i - 1 ) ; } } return max1 ; } int main ( ) { string s1 , s2 , s3 , s4 , s5 ; s1 = " abcde " ; s2 = " abcsd " ; s3 = " bcsdf " ; s4 = " abcda " ; s5 = " abced " ; vector < string > v ; v . push_back ( s1 ) ; v . push_back ( s2 ) ; v . push_back ( s3 ) ; v . push_back ( s4 ) ; v . push_back ( s5 ) ; int m = v [ 0 ] . size ( ) ; cout << MaxLength ( v , 0 , m ) + 1 << endl ; return 0 ; }