题目:
Write a function to find the longest common prefix string amongst an array of strings.
思路:查找最长的通配符,可以找一个最短的字符串作为标准,依次使用这个字符串中的字符和其他字符串的相应位置进行比较,如果相等,那么继续,如果不等,那么至此就是最长的通配符。这是暴力方法
其实查找最长的通配符最好的数据结构是Trie树,在对所有的字符串创建字典树时就可知道最长的通配符。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
Write a function to find the longest common prefix string amongst an array of strings.
找最长的通配符号
*/
string LongestCommonPrefix(vector<string>& vec)
{
int i,j;
int pos=0;
int len = vec[0].length();
for(i=1;i<vec.size();i++)
if(vec[i].length() < len)
pos =i;
for(i=0;i<vec[pos].length();i++)
{
for(j=0;j<vec.size();j++)
if(vec[pos][i] != vec[j][i])
break;
if(j<vec.size())
break;
}
return string(vec[pos],0,i);
}
int main()
{
vector<string> vec;
string str("abcfgds");
string str1("abcfda");
string str2("abcfgdd");
string str3("abcad");
string str4("abcfdfd");
vec.push_back(str);
vec.push_back(str1);
vec.push_back(str2);
vec.push_back(str3);
vec.push_back(str4);
cout<<LongestCommonPrefix(vec)<<endl;
return 0;
}