# 最长公共前缀

### 题目连接

https://leetcode-cn.com/problems/longest-common-prefix/

### 题目解析

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
{
return "";
}
for(int i=0;i<strs[0].size();++i)
{
for(int j=1;j<strs.size();++j)
{
if(strs[j][i]!=strs[0][i])
{
return strs[0].substr(0,i);//没有开辟新串
}
}
}
return strs[0];
}
};



，其中 mid = \frac{i+j}{2} 2i+j。

public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
return longestCommonPrefix(strs, 0 , strs.length - 1);
}

private String longestCommonPrefix(String[] strs, int l, int r) {
if (l == r) {
return strs[l];
}
else {
int mid = (l + r)/2;
String lcpLeft =   longestCommonPrefix(strs, l , mid);
String lcpRight =  longestCommonPrefix(strs, mid + 1,r);
return commonPrefix(lcpLeft, lcpRight);
}
}

String commonPrefix(String left,String right) {
int min = Math.min(left.length(), right.length());
for (int i = 0; i < min; i++) {
if ( left.charAt(i) != right.charAt(i) )
return left.substring(0, i);
}
return left.substring(0, min);
}


©️2019 CSDN 皮肤主题: 护眼 设计师: 闪电赇