OpenJudge 6252 带通配符的字符串匹配

描述

通配符是一类键盘字符,当我们不知道真正字符或者不想键入完整名字时,常常使用通配符代替一个或多个真正字符。通配符有问号(?)和星号(*)等,其中,“?”可以代替一个字符,而“*”可以代替零个或多个字符。 

你的任务是,给出一个带有通配符的字符串和一个不带通配符的字符串,判断他们是否能够匹配。 

例如,1?456 可以匹配 12456、13456、1a456,但是却不能够匹配23456、1aa456; 

2*77?8可以匹配 24457798、237708、27798。


  简单的递归,要注意的是题目的坑点,有30分,是*为零个字符的情况。这当中有20分是*在字符串当中,有10分是*在字符串末尾,要分开来特殊化处理。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;

string str1, str2;
int len1, len2;
bool vis = false;

int DP(int x, int y)
{
	if(vis) return 0;
	if(x == len1 && y == len2 && (str1[x] == str2[y] || str1[x] == '*' || str1[x] == '?')) {
		printf("matched");
		vis = true;
		return 0;
	}
	if(x > len1 || y > len2) {
		return 0;
	}
	
	if(str1[x] == '*') {
		DP(x, y+1);
		DP(x+1, y);
	}
	if(str1[x] == '*' || str1[x] == '?' || str1[x] == str2[y]) {
		DP(x+1, y+1);
		if(str1[x+1] == '*') DP(x+1, y);
	}
	
	return 0;
}

int main()
{
	cin>>str1>>str2;
	len1 = str1.size();
	len2 = str2.size();
	str1 = " " + str1;
	str2 = " " + str2;

	
	DP(1, 1);
	
	if(!vis) printf("not matched");
	
	return 0;
}

  动规写法。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;

string str1, str2;
int len1, len2;
bool dp[24][24];

int main()
{
	cin>>str1>>str2;
	len1 = str1.size();
	len2 = str2.size();// cout<<len1<<" "<<len2;
	str1 = " " + str1;
	str2 = " " + str2;
	
	dp[0][0] = true;
	for(int i = 1; str1[i] == '*'; i++)
		dp[i][0] = true;
		
	
	for(int i = 1; i <= len1; i++)
		for(int j = 1; j <= len2; j++)
		{
			if(str1[i] == '?') {
				dp[i][j] = dp[i-1][j-1];
				continue;
			}
				
			if(str1[i] == '*') {
				dp[i][j] = (dp[i-1][j-1] || dp[i-1][j] || dp[i][j-1]);
				continue;
			}
				
			if(str1[i] == str2[j]) dp[i][j] = dp[i-1][j-1];
		}
	
	if(dp[len1][len2]) printf("matched");
	else printf("not matched");
	
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值