Name: Longest Common Prefix
Difficulty: Easy
Description: Find the longest common prefix amongst several words
Example:
Given ["flower", "flow", "flight"], return "fl" Given ["car", "tree"], return "" Given ["c"] return "c"
I was pretty tired when coding this one, time for bed 🙂
string longestCommonPrefix(vector<string>& strs) {
const string& word = strs[0];
if (strs.size() == 1) return word;
for (auto i = 0; i < word.size(); ++i) {
for (auto j = 1; j < strs.size(); ++j) {
if (strs[j][i] != word[i]) {
return i > 0 ? word.substr(0, i) : "";
}
}
}
return word;
}