Write a function to find the longest common prefix string amongst an array of strings.
(1)需要注意strs为空的情况
(2)需要注意每个字符串的长度是不一样的,不能超出字符串组长度的最小值
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string longestCommonPrefix(vector<string> &strs) {
string res;
if(strs.size() == 0)
return res;
if(strs.size() == 1)
return strs.at(0);
size_t length = strs.size();
bool same = true;
size_t index = 0;
size_t min = INT_MAX;
for(size_t i = 0;i<length;i++)
{
if(min > strs.at(i).length())
{
min = strs.at(i).length();
}
}
while(same)
{
if(index >= min)
return res;
size_t i;
for(i = 1;i<length;i++)
{
if(strs.at(i)[index] != strs.at(0)[index])
{
break;
}
}
if(i == length)
{
res.push_back(strs.at(0)[index]);
index++;
}else{
same = false;
}
}
return res;
}
int main(void)
{
vector<string> strs;
strs.push_back("addaa");
strs.push_back("add");
cout << longestCommonPrefix(strs) << endl;
system("pause");
return 0;
}