Write a function to find the longest common prefix string amongst an array of strings.
上图每一列代表strs[0],strs[1],strs[2].......
为了解决该问题,每次比较一行,首先比较第0行,然后第一行......
// test14LongestCommonPrefix.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "string"
#include "vector"
using std::string;
using std::vector;
string longestCommonPrefix(vector<string>& strs);
int _tmain(int argc, _TCHAR* argv[])
{
vector <string> strs = { "hello", "helloaaa" };
string res = longestCommonPrefix(strs);
return 0;
}
string longestCommonPrefix(vector<string>& strs)
{
int nums = strs.size();
if (nums == 0)
return "";
else if (nums <= 1)
return strs[0];
string predix;
char temp;
for (int i = 0; i < strs[0].size(); i++)
{
temp = strs[0][i];
for (int j = 1; j < nums; j++)
{
if (strs[j][i] != temp)
return strs[0].substr(0, i);
}
}
return strs[0];
}