Wildcard Matching

Wildcard Matching

字符串的模式匹配,类似正则

总体思想:

把模式串按照 * 分割成字串,如果匹配串中按顺序分布着这些字串,那么就OK

本着这个思想实现的是:贪心算法

方法一,用字串比较的方法:

class Solution:
    # @param s, an input string
    # @param p, a pattern string
    # @return a boolean
    def isMatch(self, s, p):
        n = len(s)
        psplit = p.split("*")
        # No "*"
        if len(psplit) == 1:
            if n == len(p) and self.strMatch(s, psplit[0]):
                return True
            else:
                return False
        # Delete "" in psplit
        pPureList = [x for x in psplit if x]
        # Length compare
        pPureStr = "".join(pPureList)
        if len(pPureStr) > n: return False
        
        # Head is not "*"
        if p[0] != "*":
            if not self.strMatch(s[:len(pPureList[0])], pPureList[0]):
                return False
        # Tail is not "*"
        if p[-1] != "*":
            if not self.strMatch(s[n-len(pPureList[-1]):], pPureList[-1]):
                return False
        
        i = 0
        for one in pPureList:
            oneLen = len(one)
            while oneLen + i <= n and not self.strMatch(s[i:i+oneLen], one):
                i += 1
            if oneLen + i > n:
                return False
            else:
                i += oneLen
        return True
    
    def strMatch(self, a, b):
        # a and b is same lenght, only b has "?"
        i = 0
        n = len(a)
        while i < n:
            if b[i] != "?" and a[i] != b[i]:
                return False
            i += 1
        return True
        

方法二,脚标控制,参考了Discuss里面的思想:

class Solution:
    # @param s, an input string
    # @param p, a pattern string
    # @return a boolean
    def isMatch(self, s, p):
        ns, np = len(s), len(p)
        i, j, ni, nj = 0, 0, 0, -1
        while i < ns:
            if j < np and (p[j] == "?" or s[i] == p[j]):
                i, j = i+1, j+1
            elif j < np and p[j] == "*":
                ni, nj = i, j+1
                j += 1
            elif nj != -1:
                ni += 1
                i, j = ni, nj
            else:
                return False
        while j < np and p[j] == "*":
            j += 1
        return j == np


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值