★leetcode44_Wildcard Matching

本文介绍了通配符匹配算法的两种实现方式:动态规划和回溯结合贪婪算法。通过对比这两种方法,阐述了如何有效解决通配符匹配问题,并提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.问题描述

Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

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", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

即实现通配符匹配,与正则匹配不同,通配符'?'匹配任意单个字符(不包括空字符),通配符'*'匹配任意多个任意字符(包括空字符)。


二.代码编写

因为实现不小心点开了'Show Tags',再加上之前写正则匹配那道题实在印象深刻,就直接上手写dp了,用dp的话规则还算简单,实现也很简单,但是提交的时候发现Memory Limit Exceed,这很正常,就像用递归会导致TLE一样,dp是用空间换时间嘛。但是代码还是贴出来,如下:

'''
@ author: wttttt at 2016.10.29
@ problem description see: https://leetcode.com/problems/wildcard-matching/
@ solution explanation see: http://blog.youkuaiyun.com/u014265088
@ github:https://github.com/wttttt-wang/leetcode
@ dynamic programming
@ Memory limit exceeded
'''
class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        len_s = len(s)
        len_p = len(p)
        if len_s == 0:
            return True if (p=='*' or len_p==0) else False
        if len_p ==0:
            return False
        dp = [[0 for i in range(len_p+1)] for j in range(len_s+1)]
        dp[0][0] = 1
        # initialize dp[0][j]
        for j in range(1,len_p+1):
            if p[j-1] == '*':
                dp[0][j] = dp[0][j-1]
        for i in range(1,len_s+1):
            for j in range(1,len_p+1):
                if dp[i-1][j-1] == 1 and (s[i-1]==p[j-1] or p[j-1]=='*' or p[j-1]=='?') \
                        or(p[j-1]=='*' and (dp[i-1][j] == 1 or dp[i][j-1]==1)):
                    dp[i][j] = 1
        if dp[len_s][len_p] == 1:
            return True
        else:
            return False
so = Solution()
s = 'aaafwf'
p = 'aafsf'
print so.isMatch(s,p)

三.算法优化

一开始看到空间溢出的时候,结合tags里的backtracking和greedy,就想dp算法还能剪枝?想了半天没想出头绪,然后百度了一下,发现其实用backtracking结合greedy的解法那是真的简单啊。

通配符匹配的难点就是*的匹配-可能匹配0到多个。所以基本的算法思想就是对‘*’首先贪心匹配0个字符,当不断移动指针发现后续导致了not match的时候回溯到之前的‘*’和s中'*'之前默认匹配位置的下一个(即使'*'匹配两个字符)。这样不断推出,回溯,每次回溯'*'多匹配一个字符。 算法编写的时候还有一个注意点就是停止条件~

代码如下:

'''
@ author: wttttt at 2016.10.29
@ problem description see: https://leetcode.com/problems/wildcard-matching/
@ solution explanation see: http://blog.youkuaiyun.com/u014265088
@ github:https://github.com/wttttt-wang/leetcode
@ backtracking with greedy
@ backtracking: when not match, then backtracking
@ greedy: '*' match null firstly, when not match, then match '*' to one character,
    if still not match, then match '*' to several characters.[match one more character once backtracking]
'''
class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        len_s = len(s)
        len_p = len(p)
        ps = 0  # pointer of s
        pp = 0  # pointer of p
        flag_xing = -1  # point of the last appeared '*'
        flag_pos = -1   # point of the last pos of s which '*' matched
        while ps<len_s:
            if pp<len_p and (s[ps] == p[pp] or p[pp] == '?'):
                ps += 1
                pp += 1
                continue
            elif pp<len_p and p[pp] == '*':
                flag_xing = pp
                flag_pos = ps
                pp += 1
                continue
            #else:   # not match
            if flag_xing != -1:   # if there exists a '*' before
                pp = flag_xing+1
                flag_pos += 1
                ps = flag_pos
                continue
            return False
        while pp<len_p and p[pp]=='*':
            pp += 1
        if pp == len_p:
            return True
        return False


so = Solution()
s = 'aa'
p = '*'
print so.isMatch(s,p)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值