#include <iostream>
#include <string>
#include <vector>
#include<algorithm>
using namespace std;
/*编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""*/
string longestCommonPrefix(vector<string> &strs)
{
string result;
/*判定向量是否为空*/
if (strs.empty())
{
result = {""};
}
else
{
size_t s = strs.size();
if (s == 1)
{
return strs[0];
}
else if (s > 1)
{
/*构造向量字符串元素跳过对{"c", "c",...}和{"","",....}类似的向量元素的判定*/
strs[0] = strs[0] + "10lo";
strs[1] = strs[1] + "l01o";
/*初始化计数器*/
size_t count = 0;
/*定义数组,保存对比的计数结果*/
vector<int> arr;
for (size_t i = s - 1; i > 0; i--)
{
for (size_t j = 0;; j++)
{
if (strs[0][j] != strs[i][j])
{
break;
}
count++;
}
arr.push_back(count);
/*重新初始化计数器*/
count = 0;
}
size_t sa = arr.size();
/*从小到大排序*/
sort(arr.begin(), arr.end());
/*首位元素就是最终结果*/
if (arr[0] == 0)
{
result = {""};
}
else
{
for (size_t i = 0; i < arr[0]; i++)
{
result.push_back(strs[1][i]);
}
}
}
}
return result;
}
int main(int argc, char const *argv[])
{
vector<string> a = {"boot", "boom", "boor", "boall"};
vector<string> b = {"baac", "bacc", "b"};
vector<string> c = {"flower"};
vector<string> d = {"",""};
vector<string> e =
{
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
};
cout << longestCommonPrefix(a) << endl;
cout << longestCommonPrefix(b) << endl;
cout << longestCommonPrefix(c) << endl;
cout << longestCommonPrefix(d) << endl;
cout << longestCommonPrefix(e) << endl;
return 0;
}
|