-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestcommonprefix.cpp
More file actions
32 lines (29 loc) · 960 Bytes
/
longestcommonprefix.cpp
File metadata and controls
32 lines (29 loc) · 960 Bytes
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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return ""; // Edge case: Empty input
for (int i = 0; i < strs[0].size(); i++) { // Scan column-wise
char c = strs[0][i]; // First string's character at position i
for (int j = 1; j < strs.size(); j++) { // Compare with all strings
if (i >= strs[j].size() || strs[j][i] != c) // Mismatch
return strs[0].substr(0, i);
}
}
return strs[0]; // If no mismatches, return the first string
}
};
// **Main function to test locally (Not needed for LeetCode)**
int main() {
Solution sol;
int n;
cin >> n; // Number of strings
vector<string> strs(n);
for (int i = 0; i < n; i++) {
cin >> strs[i];
}
cout << sol.longestCommonPrefix(strs) << endl;
return 0;
}