1
+ // Begin
2
+ // Take the array of strings as input.
3
+ // function matchedPrefixtill(): find the matched prefix between string s1 and s2 :
4
+ // n1 = store length of string s1.
5
+ // n2 = store length of string s2.
6
+ // for i = 0, j = 0 to i <= n1 – 1 && j <= n2 - 1
7
+ // if s1[i] != s2[j]
8
+ // break
9
+ // result.push_back(s1[i])
10
+ // return result
11
+ // End
12
+ // Begin
13
+ // function matchedPrefix(): returns the longest matched prefix from the array of strings:
14
+ // for int i = 1 to n - 1
15
+ // pre = matchedPrefixtill(pre, a[i])
16
+ // return pre.
17
+ // End
18
+
19
+ #include < bits/stdc++.h>
20
+ using namespace std ;
21
+
22
+ string matchedPrefixtill (string s1, string s2) {
23
+ string res;
24
+ int n1 = s1.length (); // store length of string s1.
25
+ int n2 = s2.length (); // store length of string s2.
26
+ for (int i = 0 , j = 0 ; i <= n1 - 1 && j <= n2 - 1 ; i++, j++) {
27
+ if (s1[i] != s2[j])
28
+ break ;
29
+ res.push_back (s1[i]);
30
+ }
31
+ return (res);
32
+ }
33
+ string matchedPrefix (string a[], int n) {
34
+ string pre = a[0 ];
35
+ for (int i = 1 ; i <= n - 1 ; i++)
36
+ pre = matchedPrefixtill (pre, a[i]);
37
+ return (pre);
38
+ }
39
+ int main () {
40
+ string a[] = {" Tutorialspoint" , " Tutor" , " Tutorials" }; // taking inputs
41
+ int n = sizeof (a) / sizeof (a[0 ]);
42
+ string res = matchedPrefix (a, n);
43
+ if (res.length ())
44
+ cout<<" Longest common subsequence is matched - " <<res.c_str ();
45
+ else
46
+ cout<<" No matched prefix" ;
47
+ return (0 );
48
+ }
0 commit comments