-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Common Prefix in an Array.cpp
60 lines (52 loc) · 1.15 KB
/
Longest Common Prefix in an Array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<bits/stdc++.h>
using namespace std;
class Solution{
public:
string longestCommonPrefix (string arr[], int N)
{
sort(arr,arr+N);
string temp1=arr[0];
string temp2=arr[N-1];
string ans="";
for(int i=0; i<min(temp1.size(),temp2.size()); i++)
{
if(temp1[i]==temp2[i])
{
ans+=temp1[i];
}
else
{
break;
}
}
if(ans=="")
return "-1";
return ans;
}
};
int main()
{
int t; cin >> t;
while (t--)
{
int n; cin >> n;
string arr[n];
for (int i = 0; i < n; ++i)
cin >> arr[i];
Solution ob;
cout << ob.longestCommonPrefix (arr, n) << endl;
}
}
// int main()
// {
// int t; cin >> t;
// while (t--)
// {
// int n; cin >> n;
// string arr[n];
// for (int i = 0; i < n; ++i)
// cin >> arr[i];
// Solution ob;
// cout << ob.longestCommonPrefix (arr, n) << endl;
// }
// }