类似正则表达式的匹配问题:
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;
}