#-*-Coding:utf8-*-
‘‘‘
https://oj.leetcode.com/problems/regular-expression-matching/
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).
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", "A *") →true
IsMatch ("AA", ". *") →true
IsMatch ("AB", ". *") →true
IsMatch ("AaB", "C*a*b") →true
===comments by dabay===
This problem should be used in a dynamic planning approach. I just want to say, big head!
Establish a two-dimensional array, the first dimension is S-based, the second dimension is P-based. (Order is important)
Initialize Res[0], which is more than 1 longer than p, that is, the first true of many. At the same time, consider the case where the number of even starts in P is *, initialize the corresponding true. The other is false.
Then each time we put an S element in, try to match the whole p.
Three cases: (res[i+1][j+1 per update)
If P[J] is not. and *, that is the general comparison, while observing res[i][j].
If P[J] is., no comparison is required, depending on the value of Res[i][j].
If P[J] is *,
Consider a match 0 times: Determine if res[i+1][j-1] is true
Consider the case of a match once: determine if RES[I+1][J] is true
Consider the case of multiple matches: Judging if the characters match, and judging res[i][j+1]
‘‘‘
Class Solution:
# @return A Boolean
def isMatch (self, S, p):
res = []
Defaultrow = [FALSE] + [False for _ in P]
Res.append (List (Defaultrow))
Res[0][0] = True
For x in Xrange (Len (P)):
If p[x] = = ' * ':
RES[0][X+1] = res[0][x-1]
For i in Xrange (Len (s)):
Res.append (List (Defaultrow))
For j in Xrange (Len (P)):
If P[J]! = ' * ':
if (s[i] = = P[j] or p[j] = = '. ') and Res[i][j]:
RES[I+1][J+1] = True
Elif P[j] = = '. ':
If RES[I][J]:
RES[I+1][J+1] = True
ELSE: # *
#匹配0次
If RES[I+1][J-1]:
RES[I+1][J+1] = True
#匹配1次
If RES[I+1][J]:
RES[I+1][J+1] = True
#匹配多次
if (s[i] = = P[j-1] or p[j-1] = = '. ') and res[i][j+1]:
RES[I+1][J+1] = True
return Res[-1][-1]
def main ():
Sol = solution ()
s = "AaB"
p = "C*a*b"
Print Sol.ismatch (S, p)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [PYTHON] [DP] REGULAR EXPRESSION MATCHING