Regular Expression Matching

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where: 

  • '.' Matches any single character.​​​​
  • '*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

Example:

Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

bool isMatch(string astring b)
{
    int n = a.size(), m = b.size();
    vector<vector<bool>> dp(n + 1vector<bool>(m + 10));
    for (int i = 0i <= ni++)
    {
        for (int j = 0j <= mj++)
        {
            if (i == 0)
            {
                dp[i][j] = (j == 0);
                if (j && b[j - 1] == '*')
                    dp[i][j] = dp[i][j - 2];
            }
            else
            {
                //one character match
                if (j && b[j - 1] == '.')
                {
                    dp[i][j] = dp[i - 1][j - 1];
                }

                //if 0 or more character match
                else if (j && b[j - 1] == '*')
                {
                    //if 0 or more character match
                    if (b[j - 2] == '.')
                    {
                        dp[i][j] = (dp[i - 1][j] ||
                                    dp[i][j - 2]);
                    }
                    else
                    {

                        if (a[i - 1] == b[j - 2])
                        {
                            dp[i][j] = (dp[i - 1][j] ||
                                        dp[i][j - 2]);
                        }
                        else
                        {
                            dp[i][j] = dp[i][j - 2];
                        }
                    }
                }
                else if (i && j)
                {
                    dp[i][j] = (a[i - 1] == b[j - 1] &&
                                dp[i - 1][j - 1]);
                }
            }
        }
    }
    return dp[n][m];
}

int main()
{
    string s = "aa"p = "a*";

    if (isMatch(sp))
        cout << "true";
    else
        cout << "false";

    return 0;
}


No comments:

Post a Comment