解法一
- 思路:
写的第一个版本,知道是动态规划,但是不够简洁,因为动态方程 根本就没有写明白!!!!有点暴力的意思,其中还用到了剪枝操作 - 代码:
class Solution:
# @param {string} s
# @param {string} p
# @return {boolean}
def __init__(self):
self.isRepeat = []
def isMatch(self, s, p):
print 's=', s, 'p=', p
#剪枝操作
tmp = [s, p]
if tmp in self.isRepeat:
return
else:
self.isRepeat.append(tmp)
#when len(s) == 0
if len(s) == 0:
if (len(p) == 2 and p[1] == '*') or len(p) == 0:
return True
if len(p) >= 2 and p[1] == '*':
return self.starMatch(s, p)
else:
return False
if len(s) != 0 and len(p) == 0:
return False
#when when len(p) == 1,which means that the process would go without 'a*' or '.*'
if len(p) == 1:
if p[0] == '*':
return False
elif p[0] == '.' and len(s) == 1:
return True
elif s == p:
return True
else:
return False
#p[0] == * represents no regular matches
if p[0] == '*':
return False
if p[1] != '*':
if p[0] == '.':
return self.isMatch(s[1:], p[1:])
else:
if p[0] == s[0]:
return self.isMatch(s[1:], p[1:])
else:
return False
else:
return self.starMatch(s, p)
def starMatch(self, s, p):
''' when p[1] == '*', we need to discuss whether p[0] matches or not '''
if len(s) != 0 and (p[0] == s[0] or p[0] == '.'):
return self.isMatch(s[1:], p) or self.isMatch(s, p[2:])
else:
return self.isMatch(s, p[2:])
def main():
test = Solution()
print test.isMatch("aaaaaaaaaaaaab", "a*a*a*a*a*a*a*a*a*a*c")
if __name__ == '__main__':
main()
- AC
但是时间上比较不理想
解法二
思路:
代码:
''' Title: Regular Expression Matching Url: https://leetcode.com/problems/regular-expression-matching/ Author: halibut735 Data: 15.6.24 '''
import pdb
class Solution:
# @param {string} s
# @param {string} p
# @return {boolean}
def __init__(self):
self.count = 0
def isMatch(self, s, p):
self.whileloop = 0
self.count += 1
print 's=', s, 'p=', p
pdb.set_trace()
''' boundary conditions... '''
#when len(s) == 0
if len(s) == 0 and len(p) == 0:
return True
if len(s) != 0 and len(p) == 0:
return False
#when when len(p) == 1,which means that the process would go without 'a*' or '.*'
#p[0] == * represents no regular matches
if p[0] == '*':
return False
#when p[1] != * or len(p) == 1
if len(p) == 1 or p[1] != '*':
print 'if count' , self.count
if p[0] == '.' or (len(s) != 0 and p[0] == s[0]):
return self.isMatch(s[1:], p[1:])
else:
return False
else:
print 'else count', self.count
return self.starMatch(s, p)
def starMatch(self, s, p):
#when p[1] == '*', we need to discuss whether p[0] matches or not
while p[0] == '.' or (len(s) != 0 and p[0] == s[0]):
self.whileloop += 1
print 'whileloop: ', self.whileloop
if self.isMatch(s[1:], p):
return True
return self.isMatch(s, p[2:])
def main():
test = Solution()
print test.isMatch('a', "a*a")
if __name__ == '__main__':
main()
- result: 进入了endless loop,还没找出原因,应该比较简单。。回头再找吧!!!别忘了
Created with Raphaël 2.1.2 Memo 6.24 me 6.24 me halibut735 halibut735 记得找bug OK, maybe before 7.1 痛苦ing… Created with Raphaël 2.1.2
Start My Operation
Yes or No?\n My Subroutine