DEV Community

JOY SINHA
JOY SINHA

Posted on

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 1:

Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:

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".
Example 3:

Input: s = "ab", p = "."
Output: true
Explanation: ".
" means "zero or more (*) of any character (.)".

Constraints:

1 <= s.length <= 20
1 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, '.', and ''.
It is guaranteed for each appearance of the character '
', there will be a previous valid character to match.

*Code : - *

def isMatch(self, s: str, p: str) -> bool:
return self.isMat(s, p, len(s)-1, len(p)-1, False)

def isMat(self, s: str, p: str, si: int, pi: int, isAst):
    if pi < 0:
        return si < 0
    if p[pi] == '*':
        return self.isMat(s, p, si, pi-1, True)

    result = False
    if isAst:
        if si >= 0 and self.compare(s[si], p[pi]):
            result = result or self.isMat(s, p, si-1, pi, True) 
        result = result or self.isMat(s, p, si, pi-1, False)
    elif si >= 0 and self.compare(s[si], p[pi]):
        result = result or self.isMat(s, p, si-1, pi-1, False)

    return result

def compare(self, a, b):
    return a == b or a == '.' or b == '.'
Enter fullscreen mode Exit fullscreen mode

Enter fullscreen mode Exit fullscreen mode

Top comments (0)