14 Longest Common Prefix
string map_max(unordered_map<string, int> &map) {
int max = INT_MIN;
string max_string = "";
for (auto &i : map) {
if (i.second >= max && i.first.length() >= max_string.length()) {
max = i.second;
max_string = i.first;
}
}
return max_string;
}
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0)
return "";
unordered_map<string, int> str_freq;
for (int i = 0; i < strs.size(); i++) {
string word = strs.at(i);
for (int j = 0; j < word.length(); j++) {
string sub = word.substr(0, j + 1);
if (str_freq.find(sub) != str_freq.end()) {
str_freq.find(sub)->second++;
}
else {
// not found
str_freq.insert({ { sub },{ 1 } });
}
}
}
return map_max(str_freq);
}
int main() {
vector<string> strs = {""};
cout << longestCommonPrefix(strs) << endl;
pause();
strs = { "a", "b", "c" };
cout << longestCommonPrefix(strs) << endl;
pause();
strs = { "ab", "ab", "cc" };
cout << longestCommonPrefix(strs) << endl;
pause();
strs = { "abc", "abc", "abcd", "abcde", "ac", "ac", "ac" };
cout << longestCommonPrefix(strs) << endl;
pause();
strs = { "abc", "abc", "abcd", "abcde", "ac", "ac", "ac", "abcde","abcde","abcde","abcde","abcde","abcde",
"bca", "bca","bca","bca","bca","bca","bca","bca","bca","bca","bca","bca","bca","bca","bca", };
cout << longestCommonPrefix(strs) << endl;
pause();
}Last updated