imashutosh51

Regular Expression Matching

Oct 30th, 2022 (edited)
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. '''
  2. Check for wildcard string matching,Both problem is similar
  3. Question:
  4. '.' can match with any character
  5. 'a*' can match with '','a','aa','aaa','aaaa' can product infinite k
  6. '''
  7. def fun(s,p,i,j,dp):
  8.     if i<0 and j<0:
  9.         return True  
  10.  
  11.     if j<0:
  12.         return False
  13.  
  14.     if i<0:
  15.         while j>=0 and p[j]=='*':
  16.             j-=2
  17.         return j<0
  18.        
  19.     if dp[i][j]!=-1:
  20.         return dp[i][j]
  21.        
  22.     ans=False
  23.     if s[i]==p[j] or p[j]=='.':
  24.         ans=fun(s,p,i-1,j-1,dp)
  25.        
  26.     elif p[j]=='*':  
  27.         ans=fun(s,p,i,j-2,dp) #case1: we can skip the previous character of * completely, it consumed the previous char and make that ''
  28.         if j>0 and (s[i]==p[j-1] or p[j-1]=='.'): #we can check if prev char is matching the current str[i], so you can consider * will match the ith char and now you can check for other chars of str. Here we are not reducing the pattern because * can product infinite prev_char so may be s[i-1] can also be same as the prev char of *
  29.             ans=ans or fun(s,p,i-1,j,dp)
  30.            
  31.     dp[i][j]=ans
  32.     return ans
  33.  
  34. class Solution:
  35.     def isMatch(self,s,p):
  36.         dp=[[-1]*len(p) for _ in range(len(s))]
  37.         return fun(s,p,len(s)-1,len(p)-1,dp)
Advertisement
Add Comment
Please, Sign In to add comment