-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathsolution.cpp
48 lines (41 loc) · 1.15 KB
/
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
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans;
if (strs.empty()) {
return ans; // If the input vector is empty, return an empty string.
}
ans = strs[0];
for(int i=1; i<strs.size(); i++) {
for(int j=0; j<ans.size(); j++) {
if(strs[i][j] != ans[j]) {
ans = ans.substr(0, j);
break; // No need to continue checking for this string.
}
}
}
return ans;
}
};
int main() {
int n;
cout << "Enter the number of strings: ";
cin >> n;
vector<string> strs(n);
cout << "Enter " << n << " strings:" << endl;
for (int i = 0; i < n; i++) {
cin >> strs[i];
}
Solution solution;
string commonPrefix = solution.longestCommonPrefix(strs);
if (!commonPrefix.empty()) {
cout << "Longest Common Prefix: " << commonPrefix << endl;
} else {
cout << "There is no common prefix among the given strings." << endl;
}
return 0;
}