代码改变世界

[LeetCode]Longest Common Prefix

2014-03-11 20:04  庸男勿扰  阅读(127)  评论(0)    收藏  举报

原题链接:http://oj.leetcode.com/problems/longest-common-prefix/

题目描述:

Write a function to find the longest common prefix string amongst an array of strings.

题解:

  依然是一道分治法解的题,类似的还有http://www.cnblogs.com/codershell/p/3592992.html

复制代码
 1 class Solution {
 2 public:
 3     string lcp(string str1,string str2){
 4         int len1 = str1.length();
 5         int len2 = str2.length();
 6         int i,j;
 7         for(i=0,j=0; i<len1&&j<len2; i++,j++){
 8             if(str1[i] != str2[j] )
 9                 break;
10         }
11         return str1.substr(0,i);
12     }
13     string longestCommonPrefix(vector<string> &strs) {
14         int size = strs.size();
15         if(size == 0)
16             return "";
17         if(size == 1)
18             return strs[0];
19         vector<string> A,B;
20         for(int i=0; i<size/2; i++){
21             A.push_back(strs[i]);
22         }
23         for(int i=size/2; i<size; i++){
24             B.push_back(strs[i]);
25         }
26         return lcp(longestCommonPrefix(A),longestCommonPrefix(B));
27     }
28 };
View Code
复制代码

 

编辑推荐:
· 复杂业务系统线上问题排查过程
· 通过抓包,深入揭秘MCP协议底层通信
· 记一次.NET MAUI项目中绑定Android库实现硬件控制的开发经历
· 糊涂啊!这个需求居然没想到用时间轮来解决
· 浅谈为什么我讨厌分布式事务
阅读排行:
· 为大模型 MCP Code Interpreter 而生:C# Runner 开源发布
· 面试时该如何做好自我介绍呢?附带介绍样板示例!!!
· 复杂业务系统线上问题排查过程
· Coze Studio:字节跳动 Coze 的开源版本来了!第一时间深度解析
· 本可避免的P1事故:Nginx变更导致网关请求均响应400
点击右上角即可分享
微信分享提示