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)
    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000015944940
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞