LeetCode Everyday:坚持价值投资,做时间的朋友!!!
题目:
给你一个字符串 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 = "c*a*b"
输出: true
解释: 因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。
示例 5:
输入:
s = "mississippi"
p = "mis*is*p*."
输出: false
代码
方法一: 回溯
执行用时 :1512 ms, 在所有 Python3 提交中击败了19.97%的用户
内存消耗 :13.7 MB, 在所有 Python3 提交中击败了6.82%的用户
class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if not p:
return not s
first_match = bool(s) and p[0] in {s[0], '.'}
if len(p) >= 2 and p[1] == '*':
return (self.isMatch(s, p[2:]) or
first_match and self.isMatch(s[1:], p))
else:
return first_match and self.isMatch(s[1:], p[1:])
"""
For Example: input: x = -121
output: False
"""
s = "mississippi"
p = "mis*is*p*."
solution = Solution()
result = solution.isMatch(s, p)
print('输出为:', result) # False
方法二: 动态规划
执行用时 :56 ms, 在所有 Python3 提交中击败了86.07%的用户
内存消耗 :13.7 MB, 在所有 Python3 提交中击败了6.82%的用户
class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
cache = [[False]*(len(s)+1) for _ in range(len(p)+1)]
cache[0][0] = True
for i in range(1, len(p)):
cache[i+1][0] = cache[i-1][0] and p[i] == '*'
for i in range(len(p)):
for j in range(len(s)):
if p[i] == '*':
cache[i+1][j+1] = cache[i][j+1] or cache[i-1][j+1]
if p[i-1] == s[j] or p[i-1] == '.':
cache[i+1][j+1] |= cache[i+1][j]
else:
cache[i+1][j+1] = cache[i][j] and (p[i] == s[j] or p[i] == '.')
return cache[-1][-1]
"""
For Example: input: x = -121
output: False
"""
s = "mississippi"
p = "mis*is*p*."
solution = Solution()
result = solution.isMatch(s, p)
print('输出为:', result) # False
参考
- https://www.bilibili.com/video/BV1Tt4y1U7QP
- https://leetcode-cn.com/problems/regular-expression-matching/solution/zheng-ze-biao-da-shi-pi-pei-dong-tai-gui-hua-by-jy/