Find a string which matches all the patterns in the given array | C ++ implementation to find the string which matches all the patterns ; Function to find a common string which matches all the pattern ; For storing prefix till first most * without conflicts ; For storing suffix till last most * without conflicts ; For storing all middle characters between first and last * ; Loop to iterate over every pattern of the array ; Index of the first " * " ; Index of Last " * " ; Iterate over the first " * " ; Prefix till first most * without conflicts ; Iterate till last most * from last ; Make suffix till last most * without conflicts ; Take all middle characters in between first and last most * ; Driver Code ; Take all the strings ; Method for finding common string
#include <bits/stdc++.h> NEW_LINE using namespace std ; string find ( vector < string > S , int N ) { string pref ; string suff ; string mid ; for ( int i = 0 ; i < N ; i ++ ) { int first = int ( S [ i ] . find_first_of ( ' * ' ) ) ; int last = int ( S [ i ] . find_last_of ( ' * ' ) ) ; for ( int z = 0 ; z < int ( pref . size ( ) ) && z < first ; z ++ ) { if ( pref [ z ] != S [ i ] [ z ] ) { return " * " ; } } for ( int z = int ( pref . size ( ) ) ; z < first ; z ++ ) { pref += S [ i ] [ z ] ; } for ( int z = 0 ; z < int ( suff . size ( ) ) && int ( S [ i ] . size ( ) ) - 1 - z > last ; z ++ ) { if ( suff [ z ] != S [ i ] [ int ( S [ i ] . size ( ) ) - 1 - z ] ) { return " * " ; } } for ( int z = int ( suff . size ( ) ) ; int ( S [ i ] . size ( ) ) - 1 - z > last ; z ++ ) { suff += S [ i ] [ int ( S [ i ] . size ( ) ) - 1 - z ] ; } for ( int z = first ; z <= last ; z ++ ) { if ( S [ i ] [ z ] != ' * ' ) mid += S [ i ] [ z ] ; } } reverse ( suff . begin ( ) , suff . end ( ) ) ; return pref + mid + suff ; } int main ( ) { int N = 3 ; vector < string > s ( N ) ; s [ 0 ] = " pq * du * q " ; s [ 1 ] = " pq * abc * q " ; s [ 2 ] = " p * d * q " ; cout << find ( s , N ) ; return 0 ; }