Leetcode10.Regular Expression Matching
代码部分1 一个失败的产品
自我的失败代码部分(还没有做出来)
纯粹的靠if/else在试边界的蠢办法到后面真的是放弃了…
class Solution:
def isMatch(self, s: str, p: str) -> bool:
j = 0
oc = 0
co=0
lens = len(s)
for i in range(lens):
if j>=len(p):
if oc or co:return False
else:return True
if s[i]!=p[j] and p[j]!='.':
if p[j]=='*':
if j>0:
if s[i]==p[j-1] or p[j-1]=='.':continue
elif j<len(p)-1:
if s[i]==p[j+1] or p[j+1]=='.':
j+=2
continue
else:return False
else:return False
else:
if j<len(p)-1:
if p[j+1]!='*':False
elif p[j+1]=='*':
j+=2
co = 1
continue
else:return False
j+=1
oc = 1
return True
代码部分2 递归
小代码(没有*条件时的字符串匹配)
官方给出的代码(简介强大所以展示一下)
def match(text, pattern):
if not pattern: return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
return first_match and match(text[1:], pattern[1:])
完整代码
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if not p:
return not s
firstmatch = bool (s) and p[0] in {s[0], '.'}
if len(p)>1 and p[1]=='*':
return (self.isMatch(s,p[2:])) or (firstmatch and self.isMatch(s[1:],p))
else:
return firstmatch and self.isMatch(s[1:],p[1:])
Runtime: 1592 ms, faster than 7.75% of Python3 online submissions for Regular Expression Matching.
Memory Usage: 13.2 MB, less than 5.32% of Python3 online submissions for Regular Expression Matching.
这个Runtime和Memory Usage就是递归算法的硬伤了
代码部分3 动态规划
class Solution(object):
def isMatch(self, text, pattern):
memo = {}
def dp(i, j):
if (i, j) not in memo:
if j == len(pattern):
ans = i == len(text)
else:
first_match = i < len(text) and pattern[j] in {text[i], '.'}
if j+1 < len(pattern) and pattern[j+1] == '*':
ans = dp(i, j+2) or first_match and dp(i+1, j)
else:
ans = first_match and dp(i+1, j+1)
memo[i, j] = ans
return memo[i, j]
return dp(0, 0)
Runtime: 80 ms, faster than 52.46% of Python3 online submissions for Regular Expression Matching.
Memory Usage: 13.3 MB, less than 5.32% of Python3 online submissions for Regular Expression Matching.
未完待续。。。。