Advertisement
Guest User

Matching - ChatGPT

a guest
Feb 16th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | Software | 0 0
  1. class Solution(object):
  2.     def isMatch(self, s, p):
  3.         """
  4.        :type s: str
  5.        :type p: str
  6.        :rtype: bool
  7.        """
  8.         # Create a 2D DP table to store the matching results
  9.         dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]
  10.  
  11.         # Base case: an empty pattern matches an empty string
  12.         dp[0][0] = True
  13.  
  14.         # Handling cases where '*' can match zero characters
  15.         for j in range(1, len(p) + 1):
  16.             if p[j - 1] == '*':
  17.                 dp[0][j] = dp[0][j - 2]
  18.  
  19.         # Dynamic Programming
  20.         for i in range(1, len(s) + 1):
  21.             for j in range(1, len(p) + 1):
  22.                 if p[j - 1] == '.' or p[j - 1] == s[i - 1]:
  23.                     dp[i][j] = dp[i - 1][j - 1]
  24.                 elif p[j - 1] == '*':
  25.                     dp[i][j] = dp[i][j - 2] or (dp[i - 1][j] and (s[i - 1] == p[j - 2]  or p[j - 2] == '.'))
  26.                 else:
  27.                     dp[i][j] = False
  28.         return dp[len(s)][len(p)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement