正则表达式匹配
参考博客:参考博客
题目描述
给定一个字符串 (s) 和一个字符模式 (P)。实现支持 '.' 和 '*'的正则表达式匹配。
'.' 匹配任意单个字符。
'*' 匹配零个或多个前面的元素。
匹配应该覆盖整个字符串 (s) ,而不是部分字符串。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
解题思路
-
理解题目
1、分析题目:对于任意字符p, 有且仅有有一下四种情况:
1、 p = c (c为其他字符)
2、 p = p
3、 p = ‘.’
4、 p = ‘*’结论:
(1)、可以将p、s中的每个字符拿出,成为一组,单独进行比较, 循环每组字符直到对比完每个字符,即可得到结果
(2)、"*"需要与前一个字符一起考虑2、解题思路:
如果下个字符为"*":
(1)、s[后移0位]、 p[后移2位] 进行新一轮比较 (当s[当前位] == 其他字符 或者 为多余字符)
(2)、s[后移1位]、 p[后移0位] 进行新一轮比较 (当s[当前位] == ‘.’ 或者 p[当前位])如果下个字符不为“*”:
(1)、如果s[当前位]==p[当前位] 或者 p[当前位] = ‘.’: s[后移1位]、 p[后移1位] 进行新一轮比较
(2)、如果s[当前位]!= p[当前位] : return false
解题方法
方法一:递归法(分治法):
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if len(p)<=0: return len(s)<=0
match = len(s)>0 and (s[0]==p[0] or p[0]=='.')
if(len(p)>1 and p[1] == '*'):
return self.isMatch(s, p[2:]) or (match and self.isMatch(s[1:], p))
else:
return match and self.isMatch(s[1:], p[1:])
方法二:动态规划:
动态规划也是一种分治的思想,将问题分解成一个个子问题,通过解决所有子问题,来求得原问题的解,一般用于求解最优问题。但是跟分治法不同的地方在于,动态规划的子问题往往是相互关联的。
在动态规划中有几个比较关键的概念:子问题,状态,状态空间,初始状态,状态转移方程。
- 子问题:与原问题形式相同或者类似,只不过规模变小了,子问题都解决后,原问题即解决。
- 状态:与子问题相关的各个变量的一组取值即为状态,状态与子问题是一对一或一对多的关系,代表着子问题的解
- 状态空间:由所有状态构成的集合。
- 状态初始条件:即状态的初始状态。
- 状态转移方程:用来表示状态之间是如何转换的方程,即如何从一个或者多个已知的状态求出另一个状态,可以使用递推公式表示。
为方便起见,假定使用符号s[i:]表示字符串s中从第i个字符到最后一个字符组成的子串,p[j:]则表示模式串p中,从第j个字符到最后一个字符组成的子串,使用 match(i,j) 表示s[i:]与p[j:]的匹配情况,如果能匹配,则置为true,否则置为false。这就是各个子问题的状态。
那么对于match(i,j)的值,取决于p[j + 1]是否为’*’。
curMatch = i < len(s) and s[i] == p[j] or p[j] == ‘.’;p[j + 1] != ‘ * ’,match(i,j) = curMatch and match(i + 1, j + 1)
p[j + 1] == ‘ * ’,match(i,j) = match(i, j + 2) or curMatch and match(i + 1, j)
class Solution:
Results = []
def isMatch(self, s: str, p: str) -> bool:
self.Results = [[0]*(len(p)+1)]*(len(s)+1)
return self.match(0, 0, s, p)
def match(self, i: int, j: int, s: str, p: str) -> bool:
if self.Results[i][j]:
return self.Results[i][j] == True
if j == len(p):
ans = (i == len(s))
else:
curMatch = i<len(s) and (s[i]==p[j] or p[j]=='.')
if j+1<len(p) and p[j+1]=='*':
ans = self.match(i, j+2, s, p) or (curMatch and self.match(i+1, j, s, p))
else:
ans = curMatch and self.match(i+1, j+1, s, p)
self.Results[i][j] = ans
return ans