Longest prefix in a string with highest frequency | Java implementation of the above approach ; Function to find Longest prefix string with the highest frequency ; storing all indices where first element is found ; if the first letter in the string does not occur again then answer will be the whole string ; loop till second appearance of the first element ; check one letter after every stored index ; If there is no mismatch we move forward ; otherwise we stop ; Driver Code
import java . util . * ; class GFG { static void prefix ( char [ ] str ) { int k = 1 , j ; int n = str . length ; Vector < Integer > g = new Vector < > ( ) ; int flag = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) { g . add ( i ) ; flag = 1 ; } } if ( flag == 0 ) { System . out . println ( String . valueOf ( str ) ) ; } else { int len = g . size ( ) ; while ( k < g . get ( 0 ) ) { int cnt = 0 ; for ( j = 0 ; j < len ; j ++ ) { if ( ( g . get ( j ) + k ) < n && str [ g . get ( j ) + k ] == str [ k ] ) { cnt ++ ; } } if ( cnt == len ) { k ++ ; } else { break ; } } for ( int i = 0 ; i < k ; i ++ ) { System . out . print ( str [ i ] ) ; } System . out . println ( ) ; } } public static void main ( String args [ ] ) { String str = " abcab " ; prefix ( str . toCharArray ( ) ) ; } }