LeetCode 10 正则表达式匹配 python实现
2019-03-28 19:43
393 查看
题目:给定一个字符串 (s) 和一个字符模式 §。实现支持 ‘.’ 和 ‘*’ 的正则表达式匹配。
‘.’ 匹配任意单个字符。
‘*’ 匹配零个或多个前面的元素。
匹配应该覆盖整个字符串 (s) ,而不是部分字符串。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
示例 1:
输入: s = "aa" p = "a" 输出: false 解释: "a" 无法匹配 "aa" 整个字符串。
示例 2:
输入: s = "aa" p = "a*" 输出: true 解释: '*' 代表可匹配零个或多个前面的元素, 即可以匹配 'a' 。因此, 重复 'a' 一次, 字符串可变为 "aa"。
示例 3:
输入: s = "ab" p = ".*" 输出: true 解释: ".*" 表示可匹配零个或多个('*')任意字符('.')。
示例 4:
输入:
s = "aab" p = "c*a*b" 输出: true 解释: 'c' 可以不被重复, 'a' 可以被重复一次。因此可以匹配字符串 "aab"。
示例 5:
输入: s = "mississippi" p = "mis*is*p*." 输出: false
class Solution: def isMatch(self, s: str, p: str) -> bool: n = len(s) m = len(p) dp = [[False]*(n+1) for _ in range(m+1)] dp[0][0] = True for i in range(m): for j in range(-1, n): if j == -1: if p[i] == "*": dp[i+1][j+1] = dp[i-1][j+1] continue if p[i].isalpha(): if p[i] == s[j]: dp[i+1][j+1] = dp[i][j] elif p[i] == ".": dp[i+1][j+1] = dp[i][j] else: dp[i+1][j+1] = dp[i-1][j+1] or (dp[i+1][j] and (p[i-1] == s[j] or p[i-1] == ".")) return dp[-1][-1]
相关文章推荐
- Python实现正则表达式匹配任意的邮箱
- Python实现正则表达式匹配任意的邮箱方法
- LeetCode 10 正则表达式匹配
- LeetCode:10 正则表达式匹配 C++
- LeetCode 10 Regular Expression Matching (正则表达式匹配)
- leetcode 10 Regular Expression Matching(简单正则表达式匹配)
- Python: 正则表达式匹配多行,实现多行匹配模式
- 【LeetCode-面试算法经典-Java实现】【010-Regular Expresssion Matching(正则表达式匹配)】
- leetcode(10) - Regular Expression Matching 正则表达式匹配
- Python实现正则表达式匹配任意的邮箱
- leetcode 10 Regular Expression Matching(简单正则表达式匹配)
- Python中正则表达式对中文的匹配问题
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 邮件地址正则表达式匹配
- python正则表达式之贪婪引发的匹配无法退出,CPU 100%
- python实现统计汉字/英文单词数的正则表达式
- 使用Python正则表达式RE从CSDN博客源代码中匹配出博客信息
- Python 正则表达式(模式匹配)
- Python正则表达式的用法(1. 匹配)
- 匹配ip地址的python正则表达式,以及常用的正则表达式
- python 贪婪和非贪婪、多行匹配正则表达式小结