-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0014.LongestCommonPrefix.cpp
More file actions
31 lines (26 loc) · 935 Bytes
/
0014.LongestCommonPrefix.cpp
File metadata and controls
31 lines (26 loc) · 935 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
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
// Get min string length.
int maxLength = strs[0].length();
for (int i = 1; i < strs.size(); i++) maxLength = min(maxLength, (int)strs[i].length());
// Find longest common prefix.
int prefixLength = 0;
bool prefixClash = false;
for (; prefixLength < maxLength; prefixLength++) {
// Get common prefix.
char targetPrefix = strs[0][prefixLength];
// Check prefixes.
for (int j = 1; j < strs.size(); j++) {
// Check matching.
if (strs[j][prefixLength] == targetPrefix) continue;
// Prefix clashes.
prefixClash = true;
break;
}
if (prefixClash) break;
}
// Retrun substring.
return strs[0].substr(0, prefixLength);
}
};