码迷,mamicode.com
首页 > 其他好文 > 详细

含有通配符的字符串匹配

时间:2017-04-30 18:33:51      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:als   mat   第一个   int   turn   match   不能   else   space   

字符串匹配问题,给定两个字符串。求字符串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

含有通配符的字符串匹配

标签:als   mat   第一个   int   turn   match   不能   else   space   

原文地址:http://www.cnblogs.com/clnchanpin/p/6789796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!