方法I:枚举
依次枚举前缀,然后检验
改进1:只需从长到短枚举最短的字符串的前缀
改进2:检验前缀合法性时可以进行剪枝优化,加快搜索效率
时间复杂度不不太好分析,加上改进之后效率还不错。
方法II:字典树
时间复杂度O(nm),其中n是字符串个数,m是字符串长度
代码:
1 struct TrieNode { 2 int count; 3 map<char, TrieNode *> children; 4 TrieNode() : count(0) {} 5 }; 6 7 string longestCommonPrefix(vector<string> &strs) { 8 if (strs.empty()) return ""; 9 10 TrieNode *root = new TrieNode(); 11 root->count = 1; 12 for (auto str : strs) { 13 TrieNode *node = root; 14 for (int i = 0; i < str.length(); i++) { 15 if (node->children.find(str[i]) == node->children.end()) 16 node->children.insert(pair<char, TrieNode *>(str[i], new TrieNode())); 17 node = node->children[str[i]]; 18 node->count++; 19 } 20 } 21 22 int len = 0; 23 while (root->children.size() == 1) { 24 root = root->children.begin()->second; 25 if (root->count < strs.size()) 26 break; 27 len++; 28 } 29 30 return strs[0].substr(0, len); 31 }
方法III:
分治法(没看懂,待以后补充)