力扣的正则表达式匹配解法
题目描述:
给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。
‘.’ 匹配任意单个字符
‘*’ 匹配零个或多个前面的那一个元素
所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
示例 1:
输入:
s = “aa”
p = “a”
输出: false
解释: “a” 无法匹配 “aa” 整个字符串。
示例 2:
输入:
s = “aa”
p = “a*”
输出: true
解释: 因为 ‘*’ 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 ‘a’。因此,字符串 “aa” 可被视为 ‘a’ 重复了一次。
示例 3:
输入:
s = “ab”
p = “."
输出: true
解释: ".” 表示可匹配零个或多个(’*’)任意字符(’.’)。
示例 4:
输入:
s = “aab”
p = “cab”
输出: true
解释: 因为 ‘*’ 表示零个或多个,这里 ‘c’ 为 0 个, ‘a’ 被重复一次。因此可以匹配字符串 “aab”。
示例 5:
输入:
s = “mississippi”
p = “misisp*.”
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/regular-expression-matching
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
参考程序1:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
# 对p进行预解析,就是将"*" 和前一个字符捆绑在一起
temp, p, cc = [], p+'e', ''
for i in p:
if i != '*':
temp.append(cc)
cc = i
else:
cc += i
p = temp[1:]
# 空间复杂度将从O(|p| * |s|) 被简化成O(|p|)
resultl = [False] * (len(p) + 1)
resultc = [False] * (len(p) + 1)
resultl[0] = True
for j in range(len(p)):
if len(p[j]) == 2:
resultl[j+1] = resultl[j]
else:
break
for i in s:
for j in range(len(p)):
if p[j] == i or p[j] == '.':
resultc[j + 1] = resultl[j]
elif len(p[j]) == 2: # '.*' or 'a*'
if p[j][0] in [i, '.']:
resultc[j+1] = (resultc[j] # 0 匹配
or resultl[j] # 1 匹配
or resultl[j+1] # 2 or 更多匹配
)
else:
resultc[j+1] = resultc[j] # 0 匹配
resultl = resultc
resultc = [False] * (len(p) + 1)
return resultl[-1]
运行结果1:
参考程序2:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
lengths = len(s)
lengthp = len(p)
temp = [set() for _ in range(lengthp+1)]
temp[0].add(0)
for i in range(lengthp):
if i > 0 and not temp[i] and not temp[i-1]:
break
if p[i] == '.':
for x in temp[i]:
if x < lengths:
temp[i+1].add(x+1)
elif p[i] == '*':
if p[i-1] == '.':
minx = lengths+1
for xx in temp[i]: minx = min(minx, xx)
if i - 1 >= 0:
for xx in temp[i-1]: minx = min(minx, xx)
while minx <= lengths:
temp[i+1].add(minx)
minx += 1
else:
for x in temp[i]:
temp[i+1].add(x)
while x < lengths:
if (s[x] != p[i-1]):
break
temp[i+1].add(x+1)
x += 1
if i - 1 >= 0:
for x in temp[i-1]:
temp[i+1].add(x)
while x < lengths:
if (s[x] != p[i-1]):
break
temp[i+1].add(x+1)
x += 1
else:
for x in temp[i]:
if x < lengths and s[x] == p[i]:
temp[i+1].add(x+1)
if lengths in temp[-1]:
return True
return False
运行结果2:
参考程序3:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
result = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]
result[-1][-1] = True
for i in range(len(s), -1, -1):
for j in range(len(p) - 1, -1, -1):
temp = i < len(s) and p[j] in {s[i], '.'}
if j+1 < len(p) and p[j+1] == '*':
result[i][j] = result[i][j+2] or temp and result[i+1][j]
else:
result[i][j] = temp and result[i+1][j+1]
return result[0][0]
运行结果3: