-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsame-word.cpp
44 lines (35 loc) · 985 Bytes
/
same-word.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
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string result;
if (strs.empty()) {
return result;
}
// Sort the array
sort(strs.begin(), strs.end());
// Get the first and last strings
const string& first = strs[0];
const string& last = strs[strs.size() - 1];
// Start comparing
for (size_t i = 0; i < first.length(); i++) {
if (i >= last.length() || first[i] != last[i])
break;
result += first[i];
}
return result;
}
};
int main() {
Solution solution;
int n;
cin >> n;
vector<string> strs(n);
for (int i = 0; i < n; ++i) {
cin >> strs[i];
}
string result = solution.longestCommonPrefix(strs);
cout << "Longest Common Prefix: " << result << endl;
return 0;
}