Advertisement
Guest User

Matching - Gemini

a guest
Feb 16th, 2024
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 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.         m, n = len(s), len(p)
  9.         dp = [[False] * (n + 1) for _ in range(m + 1)]
  10.         dp[0][0] = True # Empty string matches empty pattern
  11.  
  12.         for i in range(1, m + 1):
  13.             for j in range(1, n + 1):
  14.                 if p[j - 1] == '.':
  15.                     dp[i][j] = dp[i - 1][j - 1]
  16.                 elif p[j - 1] == s[i - 1]:
  17.                     dp[i][j] = dp[i - 1][j - 1]
  18.                 elif p[j - 1] == '*':
  19.                 # Try matching zero or more of the preceding element
  20.                 # 1. Match zero times (skip '*')
  21.                     dp[i][j] = dp[i][j - 1]
  22.                 # 2. Match one or more times (match current char and try remaining pattern)
  23.                     for k in range(i):
  24.                         if dp[k][j - 1] and (p[j - 2] == '.' or p[j - 2] == s[k - 1]):
  25.                          dp[i][j] = True
  26.                          break # Optimization: stop after finding a match
  27.  
  28.         return dp[m][n]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement