Exercise a power button topic

10. The regular expression match

Give you a character string s and a law p, invite you to implement a support '' and '*' in the regular expression matching.

  '.' Matches any single character
  '*' matches zero or more of the preceding element that a
  so-called matching, to cover the entire string s, and not part of the string.

Description:

  s may be empty, and only lowercase letters az from the.
  p may be empty and contain only lowercase letters from az, and characters. and *.
  Example 1:

  Input:
    S = "AA"
    P = "A"
    Output: false
  interpretation: "a" can not match the entire string "aa".
  Example 2:

  Input:
    S = "AA"
    P = "A *"
  Output: true
  explanation: because the '*' matches zero or representatives of the foregoing that a plurality of elements, this is in front of the element 'a'. Thus, the string "aa" may be regarded as 'a' is repeated once.
  Example 3:

  Input:
    S = "ab &"
    P = "*."
  Output: true
  explained: ". *" Denotes zero or more matches ( '*') of any character ( '.').
  Example 4:

  Input:
    S = "AAB"
    P = "C * A * B"
  Output: true
  explanation: because the '*' means zero or more, where 'c' is 0, 'a' is repeated once. So it can match the string "aab".
  Example 5:

  Input:
    S = "Mississippi"
    P = "MIS * IS * P *."
  Output: false

 


class Solution:
  def isMatch(self, s: str, p: str) -> bool:
    dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]

    dp[-1][-1] = True
    for i in range(len(s), -1, -1):
      for j in range(len(p) - 1, -1, -1):
        first_match = i < len(s) and p[j] in {s[i], '.'}
        if j+1 < len(p) and p[j+1] == '*':
          dp[i][j] = dp[i][j+2] or first_match and dp[i+1][j]
        else:
          dp[i][j] = first_match and dp[i+1][j+1]
    return dp[0][0]

Guess you like

Origin www.cnblogs.com/zhaop8078/p/12500264.html