-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestCommonPrefix.cpp
More file actions
31 lines (27 loc) · 868 Bytes
/
Copy pathlongestCommonPrefix.cpp
File metadata and controls
31 lines (27 loc) · 868 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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
// This implementation takes the first string as the initial prefix,
// then compares it character by character with each subsequent string.
// If a mismatch is found, it shortens the prefix accordingly.
string longestCommonPrefix(vector<string>& strs) {
string prefix = strs[0];
for (int i=1; i<strs.size(); i++) {
string prefixNew = "";
for (int j=0; j<strs[i].size() && j<prefix.size(); j++) {
if (prefix[j] == strs[i][j]) {
prefixNew += prefix[j];
} else {
break;
}
}
if (prefixNew.empty()) {
return "";
}
prefix = prefixNew;
}
return prefix;
}
};