码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode#14 Longest Common Prefix

时间:2015-01-26 16:44:20      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

原题地址

 

方法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:

分治法(没看懂,待以后补充)

Leetcode#14 Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/boring09/p/4250379.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!