字符串通配符(OJ)

题目

描述

问题描述:在计算机中,通配符一种特殊语法,广泛应用于文件搜索、数据库、正则表达式等领域。现要求各位实现字符串通配符的算法。
要求:
实现如下2个通配符:
*:匹配0个或以上的字符(字符由英文字母和数字0-9组成,不区分大小写。下同)
?:匹配1个字符

输入

先输入一个带有通配符的字符串,再输入一个需要匹配的字符串

输出

返回匹配的结果,正确输出true,错误输出false

样例输入

te?t*.*
txt12.xls

样例输出

false

代码

字符串通配符(OJ)

#include <iostream>
#include <string>
using namespace std;
bool Ischar(char a)
{
    if (isdigit(a)||isalpha(a))
        return true;
    else
        return false;
}

bool ismatch(char *s,char *p)
{
    if (*p=='\0')
        return *s=='\0';
    else if (*p=='?')
    {
        if (Ischar(*s))
            return ismatch(s+1,p+1);
        else
            return false;
    }

    else if (*p!='*')
    {
        if (*p==*s)
            return ismatch(s+1,p+1);
        else
            return false;
    }
    else   //p指向的值是*时
    {
      while (*p=='*')
        p++;

      while (*s!='\0')
      {
          if (ismatch(s,p))
            return true;
          else
          {
              if (Ischar(*s))
                s++;
              else
                  return false;
          }
      }
       return ismatch(s,p);
    }
}



int main()
{
   char a[100],b[100];
   gets(a);
   gets(b);
   if (ismatch(b,a))
     cout<<"true"<<endl;
   else
       cout<<"false"<<endl;
}

DP解法

#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
void fun(string pat, string dest)
{
    int patLen = pat.size();
    int destLen = dest.size();
    vector<vector<bool>> dp(patLen + 1, vector<bool>(destLen + 1, 0));
    dp[0][0] = 1;
    for (int i = 1; i <= patLen; i++)
    {
        for (int j = 1; j <= destLen; j++)
        {
            if (pat[i - 1] == '?' || abs(pat[i - 1] - dest[j - 1]) == 0 || abs(pat[i - 1] - dest[j - 1]) == 32)
            {
                dp[i][j] = dp[i - 1][j - 1];
            }
            else if (pat[i - 1] == '*')
            {
                dp[i][j] = dp[i - 1][j - 1] || dp[i][j - 1] || dp[i - 1][j];
            }
        }
    }
    if (dp[patLen][destLen])
    {
        cout<<"true"<<endl;
    }
    else
    {
        cout<<"false"<<endl;
    }
}
int main()
{
    string pat, str;
    while (cin>>pat>>str)
    {
        fun(pat, str);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值