zoukankan      html  css  js  c++  java
  • [leetcode]Regular Expression Matching @ Python

    原题地址:https://oj.leetcode.com/problems/regular-expression-matching/

    题意:

    Implement regular expression matching with support for '.' and '*'.

    '.' Matches any single character.
    '*' Matches zero or more of the preceding element.
    
    The matching should cover the entire input string (not partial).
    
    The function prototype should be:
    bool isMatch(const char *s, const char *p)
    
    Some examples:
    isMatch("aa","a") → false
    isMatch("aa","aa") → true
    isMatch("aaa","aa") → false
    isMatch("aa", "a*") → true
    isMatch("aa", ".*") → true
    isMatch("ab", ".*") → true
    isMatch("aab", "c*a*b") → true

    解题思路:正则表达式匹配的判断。网上很多的解法是用递归做的,用java和c++都可以过,但同样用python就TLE,说明这道题其实考察的不是递归。而是动态规划,使用动态规划就可以AC了。这里的'*'号表示重复前面的字符,注意是可以重复0次的。

    先来看递归的解法:

    如果P[j+1]!='*',S[i] == P[j]=>匹配下一位(i+1, j+1),S[i]!=P[j]=>匹配失败;

    如果P[j+1]=='*',S[i]==P[j]=>匹配下一位(i+1, j+2)或者(i, j+2),S[i]!=P[j]=>匹配下一位(i,j+2)。

    匹配成功的条件为S[i]=='' && P[j]==''。

    代码,TLE:

    class Solution:
        # @return a boolean
        def isMatch(self, s, p):
            if len(p)==0: return len(s)==0
            if len(p)==1 or p[1]!='*':
                if len(s)==0 or (s[0]!=p[0] and p[0]!='.'):
                    return False
                return self.isMatch(s[1:],p[1:])
            else:
                i=-1; length=len(s)
                while i<length and (i<0 or p[0]=='.' or p[0]==s[i]):
                    if self.isMatch(s[i+1:],p[2:]): return True
                    i+=1
                return False
        

    再来看动态规划的解法。

    代码:

    class Solution:
        # @return a boolean
        def isMatch(self, s, p):
            dp=[[False for i in range(len(p)+1)] for j in range(len(s)+1)]
            dp[0][0]=True
            for i in range(1,len(p)+1):
                if p[i-1]=='*':
                    if i>=2:
                        dp[0][i]=dp[0][i-2]
            for i in range(1,len(s)+1):
                for j in range(1,len(p)+1):
                    if 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][j-2] or (dp[i-1][j] and (s[i-1]==p[j-2] or p[j-2]=='.'))
                    else:
                        dp[i][j]=dp[i-1][j-1] and s[i-1]==p[j-1]
            return dp[len(s)][len(p)]
  • 相关阅读:
    Hackerrank--Savita And Friends(最小直径生成树MDST)
    Hackerrank--Kundu and Tree
    Hackerrank--String Function Calculation(后缀数组)
    Hackerrank--Ashton and String(后缀数组)
    Foundation 学习
    JS 严格模式
    判断移动设备横竖屏
    Nodejs解析HTML网页模块 jsdom
    百度Map调用
    Jade 报错
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3781773.html
Copyright © 2011-2022 走看看