I have declared a 2D array of type bool
and I want to initiate it with false
. I have this requirement for a purpose of this code (given below) which is a question on "Wild Card String Matching"
I have tried 2 ways to initialize the boolean matrix with false
. The first method is bool lookup[n + 1][m + 1]={false};
and the second method is by memset(lookup, false, sizeof(lookup));
When I am testing my code the first method is giving me a wrong answer. Why is this happening? I have attached my code herewith.
// C++ program to implement wildcard
// pattern matching algorithm
#include <bits/stdc++.h>
using namespace std;
// Function that matches input str with
// given wildcard pattern
bool strmatch(char str[], char pattern[], int n, int m)
{
// lookup table for storing results of
// subproblems
bool lookup[n + 1][m + 1];
// initailze lookup table to false
memset(lookup, false, sizeof(lookup));
// empty pattern can match with empty string
lookup[0][0] = true;
// Only '*' can match with empty string
for (int j = 1; j <= m; j++)
if (pattern[j - 1] == '*')
lookup[0][j] = lookup[0][j - 1];
// fill the table in bottom-up fashion
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];
// If characters don't match
else
lookup[i][j] = false;
}
}
return lookup[n][m];
}
int main()
{
char pattern[] = "ajjajodojei*";
char str[] = "ahdisahdisha";
if (strmatch(str, pattern, strlen(str),
strlen(pattern)))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}