LeetCode#14 - 最长公共前缀
题目描述
代码实现
class Solution
{
public:
string longestCommonPrefix(vector<string> &strs)
{
string res = "";
if(!strs.size())
return res;
for (int i = 0; i < strs[0].length(); i++)
{
char ch = strs[0][i];
for (int j = 1; j < strs.size(); j++)
{
if (strs[j][i] != ch)
return res;
}
res.push_back(ch);
}
return res;
}
};
var longestCommonPrefix = function (strs) {
var res = "";
if (strs.length === 0)
return res;
for (var i = 0; i < strs[0].length; i++) {
var ch = strs[0][i];
for (var j = 1; j < strs.length; j++) {
if (strs[j][i] != ch)
return res;
}
res += ch;
}
return res;
};
力扣题解补充算法
分治法
class Solution
{
public:
string longestCommonPrefix(vector<string> &strs)
{
if (!strs.size())
return "";
else
return longestCommonPrefix(strs, 0, strs.size() - 1);
}
string longestCommonPrefix(const vector<string> &strs, int start, int end)
{
if (start == end)
return strs[start];
else
{
int mid = (start + end) / 2;
string lcpLeft = longestCommonPrefix(strs, start, mid);
string lcpRight = longestCommonPrefix(strs, mid + 1, end);
return commonPrefix(lcpLeft, lcpRight);
}
}
string commonPrefix(const string &lcpLeft, const string &lcpRight)
{
int minLength = min(lcpLeft.size(), lcpRight.size());
for (int i = 0; i < minLength; ++i)
{
if (lcpLeft[i] != lcpRight[i])
return lcpLeft.substr(0, i);
}
return lcpLeft.substr(0, minLength);
}
};
二分查找
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
string longestCommonPrefix(vector<string> &strs)
{
if (!strs.size())
{
return "";
}
int minLength = min_element(strs.begin(), strs.end(), [](const string &s, const string &t) { return s.size() < t.size(); })->size();
int low = 0, high = minLength;
while (low < high)
{
int mid = (high - low + 1) / 2 + low;
if (isCommonPrefix(strs, mid))
{
low = mid;
}
else
{
high = mid - 1;
}
}
return strs[0].substr(0, low);
}
bool isCommonPrefix(const vector<string> &strs, int length)
{
string str0 = strs[0].substr(0, length);
int count = strs.size();
for (int i = 1; i < count; ++i)
{
string str = strs[i];
for (int j = 0; j < length; ++j)
{
if (str0[j] != str[j])
{
return false;
}
}
}
return true;
}
};