Problem:
Write a function to find the longest common prefix string amongst an array of strings.
Solution 1:My Solution
算法思路:
1.写一个求取两个字符串前缀的函数2.遍历vector数组,依次求出前缀
时间复杂度分析:O(M*N)
string commonPrefix(string str1, string str2)
{
int len1 = str1.length();
int len2 = str2.length();
if(0 == len1 || 0 == len2)
return "";
if(len1 > len2)
{
string temp = str1;
str1 = str2;
str2 = temp;
}
int index = len1 - 1;
while(index >= 0)
{
str1 = str1.substr(0, index + 1);
if(str2.find(str1) == 0)
return str1;
index --;
}
if(index < 0)
return "";
else return str1;
}
string longestCommonPrefix(vector<string> &strs)
{
if(strs.size() == 0)
return "";
vector<string>::iterator it = strs.begin();
string current = *it++;
for(;it != strs.end(); it++)
{
current = commonPrefix(current, *it);
}
return current;
}
Solution 2:转自网友
算法思路:
My idea is firstly sort array, then compare the first string with the last string. Time complexity is O(mnlog(n)) with m be average length of string. Although by advancing a counter and checking if every string[counter] is the same can achieve O(mn) time complexity, my solution solve the problem from an different angle, FYI.
时间复杂度分析:O(M*N*log(N))
string longestCommonPrefix(vector<string> &strs) {
sort(strs.begin(),strs.end());
int n = strs.size();
if (n == 0) return "";
if (n == 1) return strs[0];
int length = 0;
while (length < strs[0].size() && length < strs[n - 1].size() && strs[0][length] == strs[n - 1][length]) length++;
return strs[0].substr(0,length);
}