leetcode python3 通配符匹配

代码思路:基于动态规划的思想,首先进行状态方程的初始化,其中dp[0][0]表示s和p为空,其值为 true;第一行 dp[0][j],换句话说,s 为空,与 p 匹配,所以只要 p 开始为 * 才为 true。接下来设计状态转移方程, 当 s[i] == p[j],或者 p[j] == ? 那么 dp[i][j] = dp[i - 1][j - 1];当 p[j] == * 那么 dp[i][j] = dp[i][j - 1] || dp[i - 1][j] 其中dp[i][j - 1] 表示 * 代表的是空字符,例如 ab, ab*;dp[i - 1][j] 表示 * 代表的是非空字符,例如 abcd, ab*

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        dp=[[False for i in range(len(p)+1)] for i in range(len(s)+1)]
        dp[0][0]=True
        for j in range(1,len(p)+1):
            for i in range(0,len(s)+1):
                if i==0:
                    dp[i][j]=dp[i][j-1] and p[j-1]=='*'
                else:
                    if s[i-1]==p[j-1] or p[j-1]=='?':
                        dp[i][j]=dp[i-1][j-1]
                    elif p[j-1]=='*':
                        dp[i][j]=dp[i][j-1] or dp[i-1][j]
        return dp[len(s)][len(p)]
发布了30 篇原创文章 · 获赞 0 · 访问量 300

猜你喜欢

转载自blog.csdn.net/m0_37656366/article/details/105191361