1. 程式人生 > >含有萬用字元的字串匹配

含有萬用字元的字串匹配

字串匹配問題,給定兩個字串,求字串2,在字串1中的最先匹配結果。字串2中可以存在'*'符號,且該符號可以代表任意字元,即字串2中存在萬用字元。

e.g. 輸入:abcdefghabef, a*f 輸出:abcdef

#include <iostream>
#include <string>
using namespace std;
bool Match(const string &s1,const string &s2,string &result)
{
	int i=0;
	if(s2.empty())//已經到了s2的尾部,說明都匹配了(s2和s1的判斷順序不能改)
		return true;
	if(s1.empty())//s1已經到了尾部,而s2還沒到尾部,說明沒有完全匹配
	{
		result="";
		return false;
	}
	if(s1[i]==s2[i])//如果相等,則匹配了一個元素,接著依次匹配下一個元素
	{
		result.push_back(s1[i]);
		Match(s1.substr(i+1),s2.substr(i+1),result);
	}
	else if(s2[i]=='*')//如果遇到*號,則跳過*號,匹配s2的其他元素
	{

		Match(s1,s2.substr(i+1),result);
	}
	else//如果s1和s2的第一個元素不相等,則匹配s1的下一個元素
	{
		result.push_back(s1[i]);
		Match(s1.substr(i+1),s2,result);
	}
}
int main()
{
	string s1="abcdefghabef";
	string s2="a*f";
	string result;
	Match(s1,s2,result);
	cout<<result<<endl;
	return 0;
}
參考

http://www.tuicool.com/articles/YZFJBb

http://wenku.it168.com/d_001232271.shtml