std::string longestCommonPrefix(std::vector<std::string>& strs) {
if (strs.empty()) return "";
std::string prefix = strs[0];
for (int i = 1; i < strs.size(); i++) {
while (strs[i].find(prefix) != 0) {
prefix = prefix.substr(0, prefix.size() - 1);
if (prefix.empty()) return "";
}
}
return prefix;
}
int main() {
std::vector<std::string> words = {"flower", "flow", "flight"};
std::cout << longestCommonPrefix(words);
return 0;
}The function starts with the first string as the prefix. It then compares this prefix with each subsequent string. If the current string does not start with the prefix, the prefix is shortened by one character from the end until it matches or becomes empty. For the input {"flower", "flow", "flight"}, the longest common prefix is "fl".
The longest common prefix is the longest substring that appears at the beginning (start) of all strings in the list.
std::string longestCommonPrefix(std::vector<std::string>& strs) {
if (strs.empty()) return "";
for (int i = 0; i < strs[0].size(); i++) {
char c = strs[0][i];
for (int j = 1; j < strs.size(); j++) {
if (i == strs[j].size() || strs[j][i] != c) {
return strs[0].substr(0, i);
}
}
}
return strs[0];
}
int main() {
std::vector<std::string> words = {"interview", "interrupt", "integrate", "integral"};
std::cout << longestCommonPrefix(words);
return 0;
}The function compares characters at each position across all strings. The first mismatch occurs at position 4 (0-based index), so the prefix is the first 4 characters "inte".
std::string longestCommonPrefix(std::vector<std::string>& strs) {
if (strs.empty()) return "";
std::string prefix = strs[0];
for (int i = 1; i < strs.size(); i++) {
while (strs[i].find(prefix) != 0) {
prefix = prefix.substr(0, prefix.size() - 1);
if (prefix.empty()) return "";
}
}
return prefix;
}The for loop uses i <= strs.size(), which causes access to strs[strs.size()] (out of bounds), leading to a runtime out_of_range exception.
Sorting the list places strings with similar prefixes together. The longest common prefix of the whole list is the prefix common to the first and last strings after sorting, reducing comparisons drastically.
