imashutosh51

Wildcard Pattern Matching

Aug 14th, 2022 (edited)
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. '''
  2. Logic:
  3. we will traverse the string from backside.
  4. ->There is three case possible here:
  5. i)pattern and string current character matches,so match for rest string ie. n-1,m-1
  6. ii)pattern current character is '?',which is equivalent to any one character,
  7.   same as case 1 so so match for rest string. ie. n-1,m-1
  8. iii)pattern current character is '*',so either * can be empty character or
  9.    some character.
  10.    a)empty character:so character index will be decreased.
  11.    b)some character:so decrease string index only,so pattern index is still
  12.      pointing to same '*',so same both condition arises again.In this
  13.      way,all 3 cases,no character,one character and some character will
  14.      be covered.
  15.  
  16. Few base case:
  17. 1.both string and pattern got over
  18. 2.string got over but pattern contains only *
  19. 3.string is remaining but pattern got over so False
  20. '''
  21. def fun(s, p, n, m, dp):
  22.     # both finished
  23.     if n < 0 and m < 0:
  24.         return True
  25.  
  26.     # pattern finished but string left
  27.     if m < 0:
  28.         return False
  29.  
  30.     # string finished but pattern left
  31.     if n < 0:
  32.         while m >= 0 and p[m] == '*':
  33.             m -= 1
  34.         return m < 0
  35.  
  36.     # memo check
  37.     if dp[n][m] != -1:
  38.         return dp[n][m]
  39.  
  40.     # normal match or '?'
  41.     if s[n] == p[m] or p[m] == '?':
  42.         dp[n][m] = fun(s, p, n-1, m-1, dp)
  43.         return dp[n][m]
  44.  
  45.     # '*'
  46.     if p[m] == '*':
  47.         dp[n][m] = fun(s, p, n-1, m, dp) or fun(s, p, n, m-1, dp)
  48.         return dp[n][m]
  49.  
  50.     # mismatch
  51.     dp[n][m] = False
  52.     return False
  53.  
  54.  
  55. class Solution:
  56.     def isMatch(self, s: str, pat: str) -> bool:
  57.  
  58.         n = len(s)
  59.         m = len(pat)
  60.  
  61.         dp = [[-1 for _ in range(m)] for _ in range(n)]
  62.  
  63.         return fun(s, pat, n-1, m-1, dp)
Advertisement
Add Comment
Please, Sign In to add comment