leetcode--10. Regular Expression Matching

来源:互联网 发布:成都市文化馆网络报名 编辑:程序博客网 时间:2024/06/15 10:09

题目:10. Regular Expression Matching

链接:https://leetcode.com/problems/regular-expression-matching/description/

题目要求实现正则表达式中的 “.” 和 “*” 。其中 “.” 可以匹配任意单个字符,“*” 可以匹配任意多个前缀字符(包括0个)。

可以用递归写,假设当前需匹配字符串为s,模式为p:

1.如果p的第二个字符不为 “*”,则当字符s[0]匹配字符p[0]且s的子串s[1:len]与p的子串p[1:len]相匹配时,s与p匹配;

2.如果p的第二个字符为 “*”,且s 的前k个字符s[0,1,2,3,...,k-1]与字符p[0]相匹配,此时如果s的k个子串(下标分别从0,1,2,...,k-1开始直到末尾)中有一个与p的子串p[2:len]相匹配(p需要跳过“*”),则s与p匹配。

python递归:

class Solution(object):    def isMatch(self, s, p):        if not p:            return not s        if len(p) == 1:            return (len(s) == 1) and (s[0] == p[0] or p[0] == '.')        if p[1] != '*':            if not s:                return False            return (s[0] == p[0] or p[0] == '.') and self.isMatch(s[1:len(s)], p[1:len(p)])        while len(s) != 0 and (s[0] == p[0] or p[0] == '.'):            if self.isMatch(s, p[2:len(p)]):                return True            s = s[1:len(s)]        return self.isMatch(s, p[2:len(p)])

实际上可以简化为DP。

设dp[i][j]的值为s[0:i]与p[0:j]是否匹配,其中[0:i]表示下标为0到i-1的子串,则:

1.若p[j-1]为 “*”,此时有两种情况可以使s[0:i]和p[0:j]匹配:一是s[0:i]与p[0:j-2]相匹配(因为 “*” 可以匹配0个字符),二是s[0:i-1]与p[0:j]匹配且字符s[i-1]与p[j-2]匹配;

2.如果p[j-1]不为 “*”,此时只需看s[0:i-1]与p[0:j-1]是否匹配且字符s[i-1]与p[j-1]是否匹配。

python DP:

class Solution(object):    def isMatch(self, s, p):        """        :type s: str        :type p: str        :rtype: bool        """        dp=[[False for col in range(len(p)+1)]for row in range(len(s)+1)]        dp[0][0]=True        for i in range(len(s)+1):            for j in range(1,len(p)+1):                if j>1 and p[j-1]=='*':                    dp[i][j]=dp[i][j-2] or (i>0 and (s[i-1]==p[j-2] or p[j-2]=='.')) and dp[i-1][j]                else:                    dp[i][j]=i>0 and dp[i-1][j-1] and (s[i-1]==p[j-1] or p[j-1]=='.')        return dp[len(s)][len(p)]


原创粉丝点击