您的位置:首页 > 其它

Longest Common Prefix(最长公共前缀)

2014-12-22 16:56 267 查看

题目:

查找字符串数组的最长的公共前缀(简称LCP),eg:"ab" 、"abc"、"abdge"其LCP="ab"

分析:

本人思路很简单,先找到最小长度的字符串的,再遍历字符串数组,把它们的每一位都和最小串比较。时间复杂度O(m*c),m为串数的个数, 其中c为最小串长, 对于n其实际上相当于常数,所以其时间复杂度为为线性的O(m)。

代码:

<span style="font-weight: normal;">class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
int index = 0, i, j;
string ans;

if (strs.empty())
return ans;

//求最小串位置
for (i = 1; i != strs.size(); ++i)
{
if (strs[i].size() < strs[0].size())
{
index = i;
}
}

for (j = 0; j != strs[index].size(); ++j)
{
for (i = 0; i != strs.size(); ++i)
{
if (strs[index][j] != strs[i][j])
return ans;
}
if (i == strs.size())
ans.push_back(strs[index][j]);
}
return ans;
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode