LeetCode 10. Regular Expression Matching python特性、动态规划、递归
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 10. Regular Expression Matching python特性、动态规划、递归
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
本文主要提供三種不同的解法,分別是利用python的特性、動態規劃、遞歸方法解決這個問題
使用python正則屬性
import reclass Solution2:# @return a booleandef isMatch(self, s, p):return re.match('^' + p + '$', s) != None
使用遞歸方法
class Solution(object):def isMatch(self, text, pattern):if not pattern:return not textfirst_match = bool(text) and pattern[0] in {text[0], '.'}if len(pattern) >= 2 and pattern[1] == '*':return (self.isMatch(text, pattern[2:]) orfirst_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] = ansreturn memo[i, j]return dp(0, 0)
后記
這題在leetcode中算是一道難題,有很多值得品味的地方,后面將繼續深入研究
參考文檔
https://blog.csdn.net/gatieme/article/details/51049244
https://leetcode.com/problems/regular-expression-matching/solution/#
總結
以上是生活随笔為你收集整理的LeetCode 10. Regular Expression Matching python特性、动态规划、递归的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 并查集解决无向图是否有环问题
- 下一篇: python 浮点数未解之谜