题目来源:https://leetcode-cn.com/problems/regular-expression-matching/
题目描述
Given an input string (s) and a pattern §, implement regular expression matching with support for ‘.’ and ‘*’.
给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。
‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).
‘.’ 匹配任意单个字符
‘*’ 匹配零个或多个前面的那一个元素
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
示例
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
解题思路
算法实现
Python3
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if not p: return not s
#若p为空,s不为空,则返回FALSE,
#若p为空,s也为空,则返回TRUE
first_match=bool(s) and p[0] in {s[0],'.'}
#如果s的第一个元素符合p,或者是个'.',则first_match=TRUE
if len(p)>=2 and p[1]=='*': #如果p中第二个是'*'
# 假设s中匹配0次,则跳过该字符和'*'
return self.isMatch(s, p[2:]) \
or first_match and self.isMatch(s[1:],p)
# 假设s中匹配至少1次,则跳过1个字符
else:
return first_match and self.isMatch(s[1:],p[1:])
#如果p中没有'#',则按正常的来