算法设计*?的匹配问题(NJAU网工)

类似正则表达式的匹配问题:

Question:

Dynamic Programming

Given a text and a wildcard pattern, implement wildcard pattern matching algorithm that finds if wildcard pattern is matched with text. The matching should cover the entire text (not partial text).

The wildcard pattern can include the characters ‘?’ and ‘*’‘?’ – matches any single character‘*’ – Matches any sequence of characters (including the empty sequence)


Text = "baaabab",
Pattern = “*****ba*****ab", output : true
Pattern = "baaa?ab", output : true
Pattern = "ba*a?", output : true

Pattern = "a*ab", output : false 



程序和注释如下:

---------------code---------------------------------------

// dp.cpp : 定义控制台应用程序的入口点。

//


#include "stdafx.h"
#include<iostream>
using namespace std;


bool match(const char *source,const char *regular)
{
//不为空则进入
const char * srecord = NULL;//记录s应该拨回到的位置
const char * record = NULL;//记录正则遇到*时的位置
while (*source)//将source中每一个字符走遍
{
if ((*source==*regular)||*regular=='?')//如果那么直接走下一轮
{
source++;
regular++;
}
else if (*regular=='*')//如果遇到了通配符*,那么记录这个位置,regular走下一个
{
srecord = source;
record = regular;//记下位置
regular++;//regular走位
}
else if (record!=NULL)
//前面二者都不符合,说明当下不相等,但是我遇见过了一次通配符号,regular限制在通配符后一位,不断的srecord++进行比较
{
regular = record+1;//去通配符的下一位
srecord++;
source = srecord;
}
else
{
//如果能来到这一步,说明直接扑街,返回0即可
return false;
}
}
while (*regular=='*')//防止后面还有*,进行此步骤
{
regular++;
}
return (*regular=='\0');//如果regular走完了,说明是true,否则是false
}


int main()
{
//source & regular
cout << match("baaabab","*****ba*****ab")<<endl;
cout << match("baaabab", "baaa?ab") << endl;
cout << match("baaabab", "ba*a?") << endl;  
cout << match("baaabab", "a*ab") << endl;
system("pause");
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值