Longest Common Prefix Matching | Set | A Java program to find the longest common prefix ; A Utility Function to find the common prefix between first and last strings ; Compare str1 and str2 ; A Function that returns the longest common prefix from the array of strings ; sorts the N set of strings ; prints the common prefix of the first and the last String of the set of strings ; Driver Code
import java . util . Arrays ; class GFG { static String commonPrefixUtil ( String str1 , String str2 ) { String result = " " ; int n1 = str1 . length ( ) , n2 = str2 . length ( ) ; for ( int i = 0 , j = 0 ; i <= n1 - 1 && j <= n2 - 1 ; i ++ , j ++ ) { if ( str1 . charAt ( i ) != str2 . charAt ( j ) ) { break ; } result += str1 . charAt ( i ) ; } return ( result ) ; } static void commonPrefix ( String arr [ ] , int n ) { Arrays . sort ( arr ) ; System . out . println ( commonPrefixUtil ( arr [ 0 ] , arr [ n - 1 ] ) ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = arr . length ; commonPrefix ( arr , n ) ; } }