LeetCode-通配符模式串匹配

题目:

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
代码(没有进行提交测试,只保留思想)

#include<iostream>
#include<vector>
#include<list>
#include<fstream>
#include<string>
#include<set>
#include<map>
#include<algorithm>
#include<stack>
#include <typeinfo> 
#include<bitset>
#include<cstdio>
#include <stdarg.h> 
#include<functional>
using namespace std;

bool is_match(string &s1,int len1,string &s2,int len2){
	int **ptr = new int*[len2];
	for (int i = 0; i < len2; i++){
		ptr[i] = new int[len1];
		memset(ptr[i],0,sizeof(int)*len1);//每一行都有len1个元素
	}
	//初始化
	if (s1[0] == s2[0])ptr[0][0] = 1;
	for (int i = 1; i < len2; i++){
		if (ptr[i - 1][0] == 1 && s2[i] == '*')ptr[i][0] = 1;
	}
	for (int i = 1; i < len2;i++){
		for (int j = 1; j < len1;j++){
			if (s1[j] == s2[i]){//两者相等
				if (ptr[j - 1][i - 1] == 1)ptr[j][i] = 1;
			}
			else{//两个字符不想等
				if (s2[i] == '?'){
					if (ptr[j - 1][i - 1] == 1)ptr[j][i] = 1;
				}
				else{//s2[i] == '*'
					if (ptr[i - 1][j - 1] == 1){
						for (int k = j; k < len1; k++)ptr[i][k] = 1;
						break;//直接跳到下一行
					}
				}
			}
		}
	}
	for (int i = 0; i < len2; i++)delete[]ptr[i];
	delete[]ptr;
	return ptr[len2][len1];
}

int main(void){
	ifstream fin("C:\\Users\\Dell\\Desktop\\data.txt");
	string str1, str2;
	while (fin>>str1>>str2){
		int size1 = str1.size();
		int size2 = str2.size();
		if (size1 == 0 || size2 == 0)cout << "false" << endl;
		if(is_match(str1,size1,str2,size2)) cout<<"yes"<< endl;//str1是不带*和?的串
		else cout <<"false"<< endl;
	}
}


这样的通配符匹配算法有两种方式:

第一种:

'*' Matches any sequence of characters (including the empty sequence).
第二种:

'*' Matches zero or more of the preceding element.
首先看第一种的解决办法,假设我们有两个串,abcdacd和a*d?cd,那么利用动态规划算法可以解决, 假设ptr[i][j]表示包含第一个串的下标为i的元素和第二串下标为j的匹配情况,那么我们就有下面的表格:


也就是说,当*可以匹配任何数量的任何字符时,只要ptr[i-1][j-1]==T,那么ptr[i-1][j].....ptr[i-1][len2-1]全部为T;

当*只能匹配它前一个字符的任意数量时,那么在不含通配符的串中,只要ptr[i-1][j]==s1[i-1],那么对应的表格的位置都是匹配的,如下图


若有疑问,可发邮件讨论!!!!!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值