Wildcard Pattern Matching

Problem Statement : 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)

We could solve this problem by applying dynamic programming.

#include<iostream>
#include <bits/stdc++.h>
using namespace std;
bool strmatch(char str[], char pattern[],int m, int n)
{
    if(m==0){return (n==0);}
    bool lookup[n+1][m+1];
    memset(lookup,false,sizeof(lookup));
    lookup[0][0]=true;
    for(int j=1;j<=m;j++)
    {
        if(pattern[j-1]=='*')
        {
            lookup[0][j]=lookup[0][j-1];
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(pattern[j-1]=='*')
            {
                lookup[i][j]=lookup[i][j-1]||lookup[i-1][j];
            }
            else if(pattern[j-1]=='?'||str[i-1]==pattern[j-1])
            {
                lookup[i][j]=lookup[i-1][j-1];
            }
            else
            {
                lookup[i][j];
            }
        }
    }
    return lookup[n][m];
}
int main()
{
    char str[] = "baaabab";
    char pattern[] = "*****ba*****ab";
    if(strmatch(str,pattern,strlen(str),strlen(pattern)))
    {
        cout<<"Yes";
    }
    else
    {
        cout<<"No";
    }
    return 0;
}

The following code optimization is as follows:

Time Complexity: O(m x n)

Auxiliary space: O(m x n)

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *