Longest Common Prefix Matching | Set | A 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 . push_back ( str1 [ i ] ) ; } return ( result ) ; } void commonPrefix ( string arr [ ] , int n ) { sort ( arr , arr + n ) ; cout << commonPrefixUtil ( arr [ 0 ] , arr [ n - 1 ] ) ; } int main ( ) { string arr [ ] = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; commonPrefix ( arr , n ) ; return 0 ; }