Advertisement
ZEdKasat

Regular Expression Match

Feb 4th, 2022
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. class Solution:
  2.     # @param A : string
  3.     # @param B : string
  4.     # @return an integer
  5.  
  6.     def checkMatch(self, A, B, a, b):
  7.        
  8.        
  9.         # if a <= 0 or b <= 0:
  10.         #     self.dp[a][b] = 1 if a == 0 and b == 0 else 0
  11.         #     return self.dp[a][b]
  12.         if a == 0 and b == 0:
  13.             return 1 if A[a] == B[b] or B[b] == "*" or B[b] == "?" else 0
  14.  
  15.         if a == -1 and b == -1:
  16.             return 1
  17.         elif a == -1 or b == -1:
  18.             return 0
  19.  
  20.         if self.dp[a][b] != -1:
  21.             return self.dp[a][b]
  22.  
  23.         if A[a] == B[b] or B[b] == "?":
  24.             self.dp[a][b] = self.checkMatch(A, B, a-1, b-1)
  25.             return self.dp[a][b]
  26.  
  27.         elif B[b] == "*":
  28.             if b == 0:
  29.                 return 1
  30.             ans = self.checkMatch(A, B, a-1, b-1) or self.checkMatch(A, B, a-1, b)
  31.             self.dp[a][b] = ans
  32.  
  33.             return self.dp[a][b]
  34.  
  35.         elif A[a] != B[b]:
  36.             self.dp[a][b] = 0
  37.             return 0
  38.  
  39.     def isMatch(self, A, p):
  40.  
  41.         pattern = [p[0]]
  42.         for x in range(1, len(p)):
  43.             if p[x-1] == p[x] == "*":
  44.                 continue
  45.             else:
  46.                 pattern.append(p[x])
  47.         pattern = "".join(pattern)
  48.            
  49.         self.dp = [[-1]*len(pattern)]*len(A)
  50.  
  51.  
  52.         return self.checkMatch(A, pattern, len(A)-1, len(pattern)-1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement