LeetCode 10. Regular Expression Matching(正则表达式匹配)

原题:

Given an input string (s) and a pattern (p), implement regular expression matching with support for ‘.’ and ‘*’.

  • ‘.’ Matches any single character.
  • ‘*’ Matches zero or more of the preceding element.

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 *.

给定一个字符串 (s) 和一个字符模式 (p)。实现支持 ‘.’ 和 ‘*’ 的正则表达式匹配。

  • ‘.’ 匹配任意单个字符。
  • ‘*’ 匹配零个或多个前面的元素。
  • 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。

说明:

  • s 可能为空,且只包含从 a-z 的小写字母。

  • p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。

Example 1:

Input:
s = "aa"
p = "a"
Output: false

Explanation: “a” does not match the entire string “aa”.

Example 2:

Input:
s = "ab"
p = ".*"
Output: true

Explanation: “.” means “zero or more () of any character (.)”.

Example 3:

Input: 10
Output: false

Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true

Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches “aab”.

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

Reference solution

采用动态规划,肯定要用空间换时间了,这里用 monkeyGoCrazy 的思路:用2维布尔数组,dp[i][j]的含义是s[0-i] 与 s[0-j]是否匹配。

  1. p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1]
  2. If p.charAt(j) == ‘.’ : dp[i][j] = dp[i-1][j-1];
  3. If p.charAt(j) == ‘*’:
    here are two sub conditions:
    1. if p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty
    2. if p.charAt(j-1) == s.charAt(i) or p.charAt(j-1) == ‘.’:
      dp[i][j] = dp[i-1][j] //in this case, a* counts as multiple a
      dp[i][j] = dp[i][j-1] // in this case, a* counts as single a
      dp[i][j] = dp[i][j-2] // in this case, a* counts as empty

这里用的bool数组比较巧妙,初始化为true。前两种情况好理解,如果匹配成功就维持之前的真假值。程序的目的是看真值能不能传递下去。如果遇到三种情况,我们就看哪种情况有真值可以传递,就继续传递下去。

图示
我用excel自己跑了下代码,画了一下示意图,下面橘黄色表示正常匹配了,蓝色表示“*”匹配空串。可以看出真值是如何传递下去的。

这里写图片描述

这里写图片描述

这里写图片描述

class Solution:
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        dp = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
        dp[0][0] = True
        for j in range(2,len(p) + 1):
            if p[j - 1] == '*':
                dp[0][j] = dp[0][j - 2]  
        for i in range(1,len(s) + 1):
            for j in range(1,len(p) + 1):
                if p[j - 1] == '*':
                    dp[i][j] = dp[i][j-2] or (s[i-1] == p[j-2] or p[j-2] == '.') and dp[i-1][j]
                    # dp[i][j] = dp[i][j-1] or dp[i][j-2] or (dp[i-1][j] and (s[i-1] == p[j-2] or p[j-2] == '.'))
                elif p[j-1] == '.' or s[i-1] == p[j - 1]:
                    dp[i][j] = dp[i-1][j-1]

        return dp[len(s)][len(p)] 

总结

应该注意的点:

  • 正则表达式符号中的 . 与 *:
    自己一直错误地理解了 ‘*’ 与 ‘.’ 的含义
    其中 ‘*’ 不应该单独理解为一个独立的个体,而应该结合 ‘*’ 前面的元素,如a*,应将a*看做是一个整体,a*可以表示空,a*也可以表示为a, aaaa, aaaa
    自己一直难以理解 .* 与 ab 的对应关系,这里可以看做先将.*变换为..,而 .. 则是可以对应任意两个字符的(除了换行符号/n),故而.*可以对应ab;
    而.*c与abc也是同理,将.*对应ab,c与c对应,可看下面正则表达式例子:
print(re.search(r"ba*c", "abc"))       
<_sre.SRE_Match object; span=(1, 3), match='bc'>
print(re.search(r".*c", "abc"))       
<_sre.SRE_Match object; span=(0, 3), match='abc'>
print(re.search(r".*", "ab"))       
<_sre.SRE_Match object; span=(0, 2), match='ab'>
print(re.search(r".*", "abc"))       
<_sre.SRE_Match object; span=(0, 3), match='abc'>
  • 递归方法与动态规划方法的使用

本题就不再是常规的直接顺序编程题,因为*可以表示任意多字符,故而需要从后向前的方式采用递归或者动态规划(将每一步的结果存起来)进行求解。

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/82467163
今日推荐