Skip to content

Instantly share code, notes, and snippets.

@m-khooryani
Created June 13, 2020 15:25
Show Gist options
  • Save m-khooryani/8679945383fd9322a236c75a2ec88a9b to your computer and use it in GitHub Desktop.
Save m-khooryani/8679945383fd9322a236c75a2ec88a9b to your computer and use it in GitHub Desktop.
Pattern Matching
This problem was asked by Facebook.
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid
regular expression and returns whether or not the string matches the regular expression.
For example, given the regular expression "ra." and the string "ray",
your function should return true. The same regular expression on the string "raymond" should return false.
Given the regular expression ".*at" and the string "chat",
your function should return true. The same regular expression on the string "chats" should return false.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(PatternMatching("cheat", "c.*t")); // true
Console.WriteLine(PatternMatching("bcd", "abcd")); // false
Console.WriteLine(PatternMatching("cheat", "c.*te")); // false
Console.WriteLine(PatternMatching("abcdef", ".***************************.")); // true
Console.WriteLine(PatternMatching("abcdef", ".***************************")); // true
}
static bool PatternMatching(string s, string pattern)
{
int n = s.Length;
int m = pattern.Length;
bool[,] dp = new bool[n + 1, m + 1];
dp[n, m] = true;
for (int j = m - 1; j >= 0; j--)
{
if (pattern[j] == '*')
{
dp[n, j] = dp[n, j + 1];
}
}
for (int i = n - 1; i >= 0; i--)
{
for (int j = m - 1; j >= 0; j--)
{
if (pattern[j] == '.' || pattern[j] == s[i])
{
dp[i, j] = dp[i + 1, j + 1];
}
else if(pattern[j] == '*')
{
dp[i, j] = dp[i, j + 1] || dp[i + 1, j];
}
}
}
return dp[0, 0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment