描述
Write a function to find the longest common prefix string amongst an array of strings.
Write a function to find the longest common prefix string amongst an array of strings.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int MIN = 100000;
string LongestCommonPrefix(vector<string> str)
{
string res;
for (int i = 0; i<str.size(); i++)
{
if (str[i].size()<MIN)
MIN = str[i].size();
}
for (int i = 0; i<MIN; i++)
{
char temp = str[0][i];
int j = 1;
for (; j<str.size(); j++)
{
if (temp != str[j][i])
break;
}
if (j != str.size())
{
if (i == 0)
return res;
else
return str[0].substr(0, i);
}
}
}
int main()
{
vector<string> str;
str.push_back("I am a man");
str.push_back("I am a seuer");
str.push_back("I am a Chinese");
str.push_back("I am a good person");
string res = LongestCommonPrefix(str);
cout << res << endl;
}