-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
39 lines (33 loc) · 862 Bytes
/
Solution.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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
string prefix = strs[0];
for (int i = 1; i < strs.size(); i++) {
int j = 0;
while (j < strs[i].size() && j < prefix.size() && strs[i][j] == prefix[j]) {
j++;
}
prefix = prefix.substr(0, j);
}
return prefix;
}
int main() {
int n;
cout << "Enter the number of strings: ";
cin >> n;
vector<string> strs(n);
cout << "Enter the strings:\n";
for (int i = 0; i < n; i++) {
cin >> strs[i];
}
string result = longestCommonPrefix(strs);
if (!result.empty()) {
cout << "Longest Common Prefix: " << result << endl;
} else {
cout << "No common prefix." << endl;
}
return 0;
}