Longest Common Prefix Matching | Set | C # 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
using System ; 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 [ i ] != str2 [ j ] ) break ; result += ( str1 [ i ] ) ; } return ( result ) ; } static void commonPrefix ( String [ ] arr , int n ) { Array . Sort ( arr ) ; Console . Write ( commonPrefixUtil ( arr [ 0 ] , arr [ n - 1 ] ) ) ; } public static void Main ( ) { String [ ] arr = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = arr . Length ; commonPrefix ( arr , n ) ; } }