您的位置:首页 > 运维架构

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

2017-08-21 23:18 337 查看
描述

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

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

例如,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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: