Advertisement
Iam_Sandeep

10. Regular Expression Matching

Aug 2nd, 2022
1,024
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. '''
  2. If length of p reaches end we should check whether we reached len(s) and return T or F
  3. But if lenght of s reach end then we shouldnt check whether we reached len(p) instead we need to wait.
  4. For e.g. s="a" p="aa*"
  5.  
  6. So three cases occur here.
  7. 1.If i has reached end
  8.     |
  9.    ---------->check j+2 is * or not. match zero characters of i fn(i,j+2)
  10. 2.If i has not reached but you found matching
  11.     |
  12.    ---------->check if j+2 is *
  13.         |
  14.        -------> do zero or more occurences match fn(i+1,j) or fn(i,j+20
  15.    ---------->match single character since its matching
  16.        
  17.  
  18. 3.You didnt find matching
  19.     |
  20.    ---------->check j+2 is * or not .match zero characters of i fn(i,j+2)
  21. '''
  22.  
  23. class Solution:
  24.     def isMatch(self, s: str, p: str) -> bool:
  25.         @cache
  26.         def dfs(i,j):
  27.             ans=False
  28.             if j>=len(p):
  29.                 return i>=len(s)
  30.            
  31.             if i==len(s):
  32.                 if j+1<len(p) and p[j+1]=='*':
  33.                     ans = ans or dfs(i,j+2)
  34.            
  35.  
  36.             elif s[i]==p[j] or p[j]=='.':
  37.                 if j+1<len(p) and p[j+1]=='*':
  38.                     ans = ans or dfs(i+1,j)
  39.                     ans = ans or dfs(i,j+2)
  40.                
  41.                 ans = ans or dfs(i+1,j+1)
  42.  
  43.             else:
  44.                 if j+1<len(p) and p[j+1]=='*':
  45.                     ans = ans or dfs(i,j+2)
  46.                    
  47.             return ans
  48.         return dfs(0,0)
  49. #2.Concise version
  50.  
  51. class Solution:
  52.     def isMatch(self, s: str, p: str) -> bool:
  53.         m,n=len(s),len(p)
  54.         @lru_cache()
  55.         def dfs(i,j):
  56.             if i>=m and j>=n:
  57.                 return True
  58.             if j>=n:return False
  59.            
  60.             match= (i<m) and (s[i]==p[j] or (p[j]=='.'))
  61.            
  62.             if j+1<n and p[j+1]=='*':
  63.                 return (dfs(i,j+2) or (match and dfs(i+1,j)))
  64.             if match:
  65.                 return dfs(i+1,j+1)
  66.             return False
  67.         return dfs(0,0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement