简繁EN

LeetCodeNo. 008

[LeetCode with Python] 10. Regular Expression Matching

Contents

Problem

Problem page: https://leetcode.com/problems/regular-expression-matching/
Topics: Dynamic Programming, Backtracking, String
Difficulty: Hard
Similar problems: (H) Wildcard 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", "cab") → true


Analysis

As with Wildcard Matching, the dynamic programming algorithm itself is no longer the hard part. It's best to handle a few special cases up front:
In the pattern string p, consecutive character-* pairs can be merged into one. For example, aa can be merged into a*, and .. can be merged into .* (the code below builds new_p_arr after the merge, but the DP still uses the original p_arr and never uses new_p_arr).
If the number of characters without a * in the pattern string p is greater than the length of the string s, the match fails.
If the pattern string p has no characters without a * and the length of the string s is 0, the match succeeds.
I've already reduced the DP matrix to two rows in my current solution. The best I can do from here is one row plus a temporary variable. I can't get it down to a 2*2 matrix.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Solution:

class Item:
def __init__(self, char, symbol):
self.char = char
self.symbol = symbol

def splitStr(self, str):
items = [ ]
index = 0
len_str = len(str)
while index < len_str:
if index + 1 >= len_str or '*' != str[index + 1]:
items.append(Solution.Item(str[index], ''))
index += 1
else:
items.append(Solution.Item(str[index], '*'))
index += 2
return items

# @param s, an input string
# @param p, a pattern string
# @return a boolean
def isMatch(self, s, p):
if '' == s and '' == p:
return True
p_arr = self.splitStr(p)
len_s = len(s)
len_p_arr = len(p_arr)

last_item = Solution.Item(None, None)
p_char_num = 0
new_p_arr = [ ]
for i in range(0, len_p_arr):
if last_item.char == p_arr[i].char and last_item.symbol == p_arr[i].symbol and '*' == p_arr[i].symbol:
pass
else:
new_p_arr.append(p_arr[i])
last_item = p_arr[i]
if '' == p_arr[i].symbol:
p_char_num += 1
if p_char_num > len_s:
return False
if 0 ==p_char_num and 0 == len_s:
return True

F = [[False for j in range(0, len_p_arr + 1)] for i in range(0, 2)]

# 3 cases for True:
# last ch matched, and this ch matcheds (right-down)
# p comes x*, and last matched (right)
# last p.symbol is x*, s comes matched ch x, and last matched (down)
for i in range(1, len_s + 1):
if 1 == i:
F[0][0] = True
for j in range(1, len_p_arr + 1):
F[0][j] = (F[0][j - 1] and '*' == p_arr[j - 1].symbol)
else:
for j in range(0, len_p_arr + 1): # cannot be F[0] = F[1]
F[0][j] = F[1][j] # due to dp array optimization
F[1][0] = False
for j in range(1, len_p_arr + 1):
if True == F[0][j - 1] and (p_arr[j - 1].char == s[i - 1] or '.' == p_arr[j - 1].char):
F[1][j] = True
elif True == F[1][j - 1] and '*' == p_arr[j - 1].symbol:
F[1][j] = True
elif True == F[0][j] and (s[i - 1] == p_arr[j - 1].char or '.' == p_arr[j - 1].char)and '*' == p_arr[j - 1].symbol:
F[1][j] = True
else:
F[1][j] = False

return F[1][len_p_arr]

Article link: https://xnerv.wang/en/leetcode-regular-expression-matching/