leetcode-44. Wildcard Matching

题目阐释:

正则匹配字符串,用程序实现

关键理解:

正则匹配,动态规划思想,一个个向后追溯,后面的依赖前面的匹配成功。
正则和待匹配的字符串长度不一,统一到正则字符串的index索引上,每次的字符串index移动,都以匹配到的正则的index为准。
正则由于*?的存在,所以有多种状态,中间状态储存都需要记录下来。然后以这些状态为动态的中转,继续判断到最后。
最后正则匹配字符串是否成功的判断依据,就是正则字符串的最大index,是否出现在遍历到最后的状态列表中。

错误之处:

多处动态变化,导致无法入手,*没有处理思路,没有找到匹配成功的条件

应用:

正则属于多条路径问题,可以推理到 多种渠道的问题,匹配成功当前的才往后推
*相当于无限向后匹配,所以无限循环使用,看能否匹配成功。
  1. Wildcard Matching

Given an input string (s) and a pattern (p), 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).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like ? or *.
Example 1:

Input:

s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:

s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Input:

s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:

Input:

s = "adceb"
p = "*a*b"
Output: true
Explanation: The first ' ' matches the empty sequence, while the second '' matches the substring "dce".

Example 5:

Input:

s = "acdcb"
p = "a*c?b"
Output: false
class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        transfer = {}
        index=0
        for char in p:
            if char=='*':
                transfer[index,char]=index
            else:
                transfer[index,char]=index+1
                index+=1
        accept=index

        # index=0
        state = {0}
        for char in s:
            state_tmp=set()
            for index in state:
                for char_prob in [char,'?','*']:
                    index_next=transfer.get((index,char_prob))
                    state_tmp.add(index_next)
            state=state_tmp
        return accept in state


if __name__=='__main__':
    s = "acdcb"
    p = "a*c?b"
    p = "a**c?d"
    st=Solution()
    out=st.isMatch(s,p)
    print(out)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值