Longest string which is prefix string of at least two strings | Java 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 .
import java . util . * ; class GFG { static int max1 = 0 ; static int MaxLength ( Vector < String > v , int i , int m ) { if ( i >= m ) { return m - 1 ; } for ( int k = 0 ; k < 26 ; k ++ ) { char c = ( char ) ( ' a ' + k ) ; Vector < String > v1 = new Vector < String > ( ) ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( v . get ( j ) . charAt ( i ) == c ) { v1 . add ( v . get ( j ) ) ; } } if ( v1 . size ( ) >= 2 ) { max1 = Math . max ( max1 , MaxLength ( v1 , i + 1 , m ) ) ; } else { max1 = Math . max ( max1 , i - 1 ) ; } } return max1 ; } public static void main ( String [ ] args ) { String s1 , s2 , s3 , s4 , s5 ; s1 = " abcde " ; s2 = " abcsd " ; s3 = " bcsdf " ; s4 = " abcda " ; s5 = " abced " ; Vector < String > v = new Vector < String > ( ) ; v . add ( s1 ) ; v . add ( s2 ) ; v . add ( s3 ) ; v . add ( s4 ) ; v . add ( s5 ) ; int m = v . get ( 0 ) . length ( ) ; System . out . print ( MaxLength ( v , 0 , m ) + 1 ) ; } }