-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestprefix.cpp
More file actions
43 lines (39 loc) · 1.26 KB
/
longestprefix.cpp
File metadata and controls
43 lines (39 loc) · 1.26 KB
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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return ""; // Edge case: Empty input
int prefixLength = 0; // Track common prefix length
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 buildPrefix(strs[0], prefixLength);
}
prefixLength++;
}
return buildPrefix(strs[0], prefixLength); // If no mismatches, return full prefix
}
private:
string buildPrefix(const string& str, int length) {
string result;
for (int i = 0; i < length; i++) {
result += str[i]; // Manually construct the prefix
}
return result;
}
};
// **Main function to test locally**
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;
}