Python3 avoid TLE by using functools.lru_cache() and precheck number of non star charecters in A and B for more info refer top down appoach


#1
import functools
import sys
sys.setrecursionlimit(10**6)
class Solution:
    # @param A : string
    # @param B : string
    # @return an integer
    def isMatch(self, A, B):
        n_nonstar = 0
        for i in range(len(B)):
            if B[i] != "*":
                n_nonstar = n_nonstar+1
        if n_nonstar>len(A):
            return 0
        if len(A)<len(B):
            for i in range(len(A),len(B)):
                if B[i] == "*":
                    A = A+" "
        m = False
        @functools.lru_cache(10**4)
        def helper(i,j):
            nonlocal m
            if j == len(B) and i == len(A):
                m = True
                return m 
            k = m
            if j>=len(B) or i>=len(A):
                return m
            elif  B[j] == "*" :
                k = (helper(i,j+1) or helper(i+1,j+1) or helper(i+1,j))
            elif B[j] == "?":
                k = helper(i+1,j+1)
            elif A[i] == B[j]:
                k =  helper(i+1,j+1)
            return k
        l =  int(helper(0,0))
        return l