标签:ant common get https longest ble pre 描述 def
原题网址:https://www.lintcode.com/problem/longest-common-prefix/description
给k个字符串,求出他们的最长公共前缀(LCP)
在 "ABCD" "ABEF" 和 "ACEF" 中, LCP 为 "A"
在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"
class Solution {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs) {
// write your code here
string result="";
int n=strs.size();
if (n==0)
{
return result;
}
int minl=INT_MAX;
for (int i=0;i<n;i++)//找到字符串中长度最小值;
{
if (strs[i].size()<minl)
{
minl=strs[i].size();
}
}
if (minl==0)
{
return result;
}
int ind=0;
while(ind<minl)//在长度最小值内搜索公共前缀;
{
char tmp=strs[0][ind];
for (int i=1;i<n;i++)
{
if (strs[i][ind]!=tmp)
{
return result;
}
}
result+=tmp;
ind++;
}
return result;
}
};
标签:ant common get https longest ble pre 描述 def
原文地址:https://www.cnblogs.com/Tang-tangt/p/9302355.html