/**
* Write a function to find the longest common prefix string amongst an array of strings.
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string longestCommonPrefix(vector<string>& strs)
{
if (strs.empty())
return "";
string prefix = strs[0];
int j = 0;
for (int i = 1; i < strs.size(); i++)
{
j = 0;
while (prefix.length() > 0 && strs[i].length() > 0 && prefix[j] && strs[i][j])
{
if (prefix[j] == strs[i][j])
{
j++;
}
else
{
break;
}
}
prefix = prefix.substr(0, j);
}
return prefix;
}
int main()
{
vector<string> strarr = {"abcd", "abef", "abfdd"};
cout << longestCommonPrefix(strarr);
system("pause");
return 0;
}
【leetcode】14. Longest Common Prefix
最新推荐文章于 2022-03-20 08:23:53 发布