The task is to implement a simple pattern matching for the whole string where the pattern may include .
and *
.
The following code makes a DFS while maintaining two pointers for the text and the pattern. It also makes use of a cache for the obvious cause of not repeating work.
I was trying to test isMatch
with several inputs but I don't see the cache is ever used ("from cache" line is never called). Can you help me show an example where the cache is being used?
Thanks
def isMatch(s, p):
cache = {}
def dfs(i, j):
print(f"dfs was called with i={i}, j={j}")
if (i, j) in cache:
print((i, j), "from cache")
return cache[(i, j)]
if i >= len(s) and j >= len(p):
return True
if j >= len(p):
return False
match = i < len(s) and (s[i] == p[j] or p[j] == ".")
if (j + 1) < len(p) and p[j+1] == "*":
cache[(i, j)] = dfs(i, j+2) or (match and dfs(i + 1, j))
return cache[(i, j)]
if match:
cache[(i, j)] = dfs(i + 1, j + 1)
return cache[(i, j)]
cache[(i, j)] = False
return False
return dfs(0, 0)
res = isMatch("aaaaaabbbbbb", "a*b*")
print(res)