题目如下:
解题思路:本题和【leetcode】97. Interleaving String非常相似,同样可以采用动态规划的方法。记dp[i][j] = 1或者0 表示pattern[0:i]是否匹配string[0:j] ,如果pattern[i] == string[j] 或者 pattern[i] == ‘?‘,那么dp[i][j] = dp[i-1][j-1];如果pattern[i] = ‘*‘ 则复杂一些,因为‘*‘可以匹配s[j-1],s[j] 或者不匹配,因此只要满足其中任意一种情况都视为匹配,得出递推关系式:dp[i][j] = max(dp[i-1][j-1],dp[i][j-1],dp[i-1][j])。
代码如下:
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ np = ‘‘ #合并连续出现的*,提高效率 for i in p: if len(np) == 0: np += i elif np[-1] == i and i == ‘*‘: continue else: np += i #pattern和string都加上‘#‘开头,处理pattern以*开头,但是又不做匹配的情况 np = ‘#‘ + np p = np s = ‘#‘ + s dp = [[0] * len(s) for i in p] #print dp dp[0][0] = 1 for i in range(len(dp)): for j in range(len(dp[i])): if p[i] == ‘*‘: if i > 0 and j > 0: dp[i][j] = max(dp[i-1][j-1],dp[i][j-1],dp[i-1][j]) elif i > 0 and j == 0: dp[i][j] = dp[i-1][j] elif i == 0 and j > 0: dp[i][j] = dp[i][j-1] elif i > 0 and j > 0 and (p[i] == ‘?‘ or p[i] == s[j]): dp[i][j] = dp[i-1][j-1] #print dp return dp[-1][-1] == 1
原文地址:https://www.cnblogs.com/seyjs/p/9559148.html
时间: 2024-10-09 12:17:27