首页 > 其他 > 详细

leetcode-44-通配符匹配

时间:2019-10-18 10:50:49      阅读:71      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

 技术分享图片

 

 技术分享图片

 

 回溯:超时

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        if not p:
            return not bool(s)
        if not s and p[0] == "*":
            return self.isMatch(s,p[1:])
        elif  s and p[0] in ["?",s[0]]:
            return self.isMatch(s[1:],p[1:])
        elif p[0] == "*":
            return self.isMatch(s[1:],p) or self.isMatch(s,p[1:])
        return False

方法二:动态规划 O(MN)

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        sl = len(s)
        pl = len(p)
        dp = [[False for _ in range(pl+1)]for _ in range(sl+1)]
        dp[0][0] = True
        for j in range(1,pl+1):
            if p[j-1] == "*":
                dp[0][j] = dp[0][j-1]
        for i in range(1,sl+1):
            for j in range(1,pl+1):
                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-1][j] or dp[i][j-1]
        return dp[-1][-1]

方法三:双指针* O(MN)

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        if not p:return not s
        #双指针
        i=j = i_shadow = 0
        #‘s‘匹配的位置
        start = -1  #*出现的位置
        while i <len(s):
            if j<len(p) and p[j] in {s[i],?}:
                i+=1
                j+=1
            #如果遇到’*‘ 先按匹配空字符处理,在不断向后扩展。
            elif j<len(p) and p[j]==*:    
                start = j
                i_shadow = i
                j += 1
            #不断扩展i,直到遇到一个s[i]==(‘*‘号后面的字符),然后再继续匹配
            elif start != -1:
                j = start+1
                i_shadow +=1
                i = i_shadow
            else:
                return False
        #s匹配完成,p可能还没有遍历完,进一步处理
        for x in p[j:]:
            if x !=*:
                return False
        return True
        #return all(x == ‘*‘ for x in p[j:])

 

leetcode-44-通配符匹配

原文:https://www.cnblogs.com/oldby/p/11697015.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!