Write a function to find the longest common prefix string amongst an array of strings.
题意是写一个函数,找到字符串最大相同的前缀。
首先以第一个字符串的子串作为参考,依次和其它字符串子串比较,如果相同,则继续,不同则返回上一次的参考子串。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string result="";
int k=0;
bool flag = true;
if(strs.size()==0)
return result;
while(strs[0][k]!='\0')
{
for (int i=1; i<strs.size(); i++)
{
if(strcmp((result+strs[0][k]).c_str(),strs[i].substr(0,k+1).c_str())!=0)
{
flag = false;
break;
}
}
if(flag)
{
result = result + strs[0][k];
k++;
}
else
{
break;
}
}
return result;
}
};