首页 > 代码库 > LeetCode(10)Regular Expression Matching

LeetCode(10)Regular Expression Matching

题目如下:

技术分享

Python代码:

# -*- coding:utf-8 -*-
def ismatch(s,p):
    #先将dp[s+1][p+1]二维数组全置为False
    dp = [[False] * (len(s) + 1) for _ in range(len(p)+1)]
    dp[0][0] = True
    for i in range(1,len(p)):
        dp[i+1][0] = dp[i-1][0] and p[i] == *
    for i in range(len(p)):
        for j in range(len(s)):
            if p[i]==*:
                # or运算相当于并,and相当于交
                dp[i+1][j+1] = dp[i-1][j+1] or dp[i][j+1]
                if p[i-1] == s[j] or p[i-1] == .:
                    # |=相当于并,&=相当于交
                    dp[i+1][j+1] |= dp[i+1][j]
            else:
                dp[i+1][j+1] = dp[i][j] and (p[i] == s[j] or p[i] == .)
    return dp[-1][-1]

print ismatch(aab,c*a*b*)

 

LeetCode(10)Regular Expression Matching