Easy
Longest Common Prefix — C++
Full explanation · Time O(n * k) · Space O(1)
// Time: O(n * k), k is the length of the common prefix
// Space: O(1)
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) {
return "";
}
for (int i = 0; i < strs[0].length(); ++i) {
for (const auto& str : strs) {
if (i >= str.length() || str[i] != strs[0][i]) {
return strs[0].substr(0, i);
}
}
}
return strs[0];
}
};