Write a function to find the longest common prefix string amongst an array of strings.
寻找最长公共前缀子串
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans = "";
bool flag;
char c;
if (!strs.size()) return ans;
if (strs.size() == 1) return strs[0];
for (int i = 0; i < strs[0].length(); i++)
{
flag = true;
c = strs[0][i];
for (int j = 1; j < strs.size(); j++)
{
if (strs[j].length() < i)
return ans;
if (strs[j][i] != c)
{
flag = false;
break;
}
}
if (flag)
ans = strs[0].substr(0, i + 1);
else break;
}
return ans;
}
};
int main()
{
Solution a;
vector <string> haha = { "aca" , "cba" };
cout << a.longestCommonPrefix(haha) << endl;
system("pause");
}