题目链接:
https://leetcode.com/problems/regular-expression-matching/
Implement regular expression matching with support for'.'
and '*'
.
'.' Matches any single character. '*' Matches zero or more of the preceding element.采用递归的方式求解
溢出:
Last executed input:"aaaaaaaaaaaaab", "a*a*a*a*a*a*a*a*a*a*c"
class Solution:
# @return a boolean
def isMatch(self, s, p):
if not s and (not p):
return True
elif not s:
if len(p)>=2:
if p[1] == '*' and self.isMatch(s,p[2:]):
return True
else:
return False
else:
return False
elif not p:
return False
else:
if len(p) >= 2 and p[1] == '*':
if s[0] == p[0] or p[0] == '.':
if (self.isMatch(s,p[2:]) or
self.isMatch(s[1:],p) or
self.isMatch(s[1:],p[2:])):
return True
else:
return False
else:
return self.isMatch(s,p[2:])
else:
if s[0]==p[0] or p[0] == '.':
return self.isMatch(s[1:],p[1:])
既然给我这样的测试程序。对症下药,在前面加了个简化p的程序。然后。。。就可以了=-=!
379ms , 排在老后面了········
class Solution:
# @return a boolean
def isMatch(self, s, p):
#simplify p
i = 0
plist = []
while (i<len(p)):
if (i+1)<len(p) and p[i+1]=='*':
if not plist or plist[-1] != p[i:i+2]:
plist.append(p[i:i+2])
i = i+2
else:
plist.append(p[i])
i = i+1
Newp = ''.join(plist)
RES = self.Matching(s,Newp)
return RES
def Matching(self, s, p):
if not s and (not p):
return True
elif not s:
if len(p)>=2:
if p[1] == '*' and self.Matching(s,p[2:]):
return True
else:
return False
else:
return False
elif not p:
return False
else:
if len(p) >= 2 and p[1] == '*':
if s[0] == p[0] or p[0] == '.':
if (self.Matching(s,p[2:]) or
self.Matching(s[1:],p) or
self.Matching(s[1:],p[2:])):
return True
else:
return False
else:
return self.Matching(s,p[2:])
else:
if s[0]==p[0] or p[0] == '.':
return self.Matching(s[1:],p[1:])
else:
return False
更快的方法应该使用栈吧。。。。。。。。。。