题目链接
https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof/
题意:
正则表达式匹配。
'.‘代表任意字符,’*'表示它前面的字符可以出现任意次(含0次)
给出字符串和模式串,问能否匹配?
题解:
解法1:暴力递归
定义递归函数(待匹配串,模式串,模式串的前一个字符orNone)
终止条件:
- 待匹配串为空,且模式串为空,表示匹配完毕,返回True
- 待匹配串为空,模式串仅为’*’,即使含有’*’,返回True
- 待匹配串为空,模式串长度大于等于2,且包含*,则模式串前进一位进行匹配
- 待匹配串为空,其他情况返回False
- 匹配串不为空,模式串为空,返回False
递归过程:
- 模式串包含’_*’(_为字母或’.’),模式串前进一位进行匹配
- 模式串当前字符为’.'或者字母,若
p[0]==s[0] or p[0]=='.'
则模式串前进一位进行匹配 - 模式串当前字符为’*’:
- 重复0次,模式串和待匹配串都前进一位进行匹配
- 重复多次,待匹配串前进一位进行匹配
代码:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
def match(s:str,p:str,lst:str) -> bool:
if len(s)==0:
if len(p)==0 or p =='*':
return True
if p[0] =='*':
return match(s,p[1:],lst)
if len(p)>=2 and p[1]=='*':
return match(s,p[1:],lst)
return False
if len(p)==0:
return False
if len(p)>1 and p[1]=='*':
return match(s,p[1:],p[0])
if p[0]!='*':
return match(s[1:],p[1:],p[0]) if p[0]==s[0] or p[0]=='.' else False
else :
return match(s,p[1:],p[0]) or (match(s[1:],p,lst) if s[0]==lst or lst=='.' else False)
return match(s,p,None)
解法2:动态规划
定义:f[i][j]表示待匹配串的前i个字符于模式串的前j个字符是否匹配。
转移方程:
- 模式串第j个字符为’*’:
- f[i][j] |= f[i][j - 2] ,表示重复0次,相当于舍弃掉模式串的’_*’(_为字母或’.’)
- if(s[i-1]==p[j-1] or p[j-1]=’.’)f[i][j] |= f[i - 1][j],表示至少可以重复一次
- 模式串第j个字符不为’*’:
- if(s[i-1]==p[j-1] or p[j-1]=’.’)f[i][j] |= f[i - 1][j - 1],表示可以匹配成功。
代码:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
def matches(i: int, j: int) -> bool:
if i == 0:
return False
if p[j - 1] == '.':
return True
return s[i - 1] == p[j - 1]
f = [[False] * (n + 1) for _ in range(m + 1)]
f[0][0] = True
for i in range(m + 1):
for j in range(1, n + 1):
if p[j - 1] == '*':
f[i][j] |= f[i][j - 2]
if matches(i, j - 1):
f[i][j] |= f[i - 1][j]
else:
if matches(i, j):
f[i][j] |= f[i - 1][j - 1]
return f[m][n]