In the Leetcode Regular Expression Matching problem solution in C# programming 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).
Leetcode Regular Expression Matching problem solution in C# programming
public class Solution {
public bool IsMatch(string s, string p) {
// Handle the case where the pattern is empty.
if (p.Length == 0)
{
return s.Length == 0;
}
// Handle the case where the pattern contains a single character.
if (p.Length == 1 || p[1] != '*')
{
if (s.Length == 0 || (p[0] != '.' && p[0] != s[0]))
{
return false;
}
return IsMatch(s.Substring(1), p.Substring(1));
}
// Handle the case where the pattern contains multiple characters.
int i = -1;
while (i < s.Length && (i < 0 || p[0] == '.' || p[0] == s[i]))
{
if (IsMatch(s.Substring(i + 1), p.Substring(2)))
{
return true;
}
i++;
}
return false;
}
}
Also read,
- Leetcode Regular Expression Matching problem solution in C++
- Leetcode Regular Expression Matching problem solution in Java
- Leetcode Regular Expression Matching problem solution in Python
- Leetcode Regular Expression Matching problem solution in C