Leetcode#14 Longest Common Prefix

原题地址

 

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

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

转载于:https://www.cnblogs.com/boring09/p/4250379.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值