Longest Common Prefix--LeetCode

题目:

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值