您的位置:首页 > 其它

LeetCode 14: Longest Common Prefix

2013-08-26 14:42 495 查看
Difficulty: 2

Frequency: 1

Problem:

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

Solution:

class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (strs.size()==0)
{
return string("");
}
return longestCommonPrefixBinaryDivide(strs, 0, strs.size()-1);
}
string longestCommonPrefixBinaryDivide(vector<string> & strs, int i_begin, int i_end)
{
if (i_begin==i_end)
return strs[i_begin];

if (i_begin==(i_end - 1))
{
int i = 0;
while (i<strs[i_begin].size()&&i<strs[i_end].size()&&strs[i_begin][i]==strs[i_end][i])
{
++i;
}
return string(strs[i_begin].substr(0, i));
}

string str1(longestCommonPrefixBinaryDivide(strs, i_begin, (i_begin+i_end)/2));
string str2(longestCommonPrefixBinaryDivide(strs, (i_begin+i_end)/2+1, i_end));
int i = 0;
while (i<str1.size()&&i<str2.size()&&str1[i]==str2[i])
{
++i;
}
// string answer(str1.substr(0, i));
return string(str1.substr(0, i));
}
};
Note:
It is like a binary search. Time complexity is O(mlogn). n is the number of strings, m is the strings' length.

Don't know if there is better answer. If you know please tell me.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: