LeetCode 10. Regular Expression Matching python特性、動態規劃、遞迴
阿新 • • 發佈:2019-01-06
前言
本文主要提供三種不同的解法,分別是利用python的特性、動態規劃、遞迴方法解決這個問題
使用python正則屬性
import re
class Solution2:
# @return a boolean
def isMatch(self, s, p):
return re.match('^' + p + '$', s) != None
使用遞迴方法
class Solution(object):
def isMatch(self, text, pattern):
if not pattern:
return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
if len(pattern) >= 2 and pattern[1] == '*':
return (self.isMatch(text, pattern[2:]) or
first_match and self.isMatch(text[1:], pattern))
else:
return first_match and self.isMatch(text[1:], pattern[1:])
使用動態規劃
動態規劃與上面的遞迴的區別就在於用空間換取了時間的複雜度
class Solution1(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)
後記
這題在leetcode中算是一道難題,有很多值得品味的地方,後面將繼續深入研究