劍指offer 正規表示式匹配

2021-09-26 14:48:21 字數 1829 閱讀 1561

劍指offer上的解法

# -*- coding:utf-8 -*-

class solution:

# s, pattern都是字串

def match(self, s, pattern):

# write code here

if s == none or pattern == none:

return false

if pattern == '':

return s == ''

if len(pattern) == 1:

return len(s) == 1 and (s[0] == pattern[0] or pattern[0] == '.')

if pattern[1] != '*':

return s!= '' and (s[0] == pattern[0] or pattern[0] == '.') and self.match(s[1:],pattern[1:])

# len(s) > 0,len(pattern) > 1 and pattern[1]== '*'的情況

while s and (s[0] == pattern[0] or pattern[0] == '.'):

# 用於跳出函式,當s迴圈到和*不匹配的時候,則開始去匹配p[2:]之後的規則

if self.match(s,pattern[2:]):

return true

s = s[1:]

# 當 s=='' 或首字母不匹配時

return self.match(s,pattern[2:])

動態規劃【反向遍歷】

動態規劃的實現思路:

* 先看下乙個是否是「*」,再看當前是否相等

* 1.若下乙個是"*",分為當前相等和當前不等 

*      1.1:當前相等dp[i][j]=dp[i][j+2] || dp[i+1][j]

*      1.2:當前不等dp[i][j]=dp[i][j+2]  

* 2.若不是"*",但是當前相等 d[i][j]= dp[i + 1][j + 1];

# -*- coding:utf-8 -*-

class solution:

# s, pattern都是字串

def match(self, s, pattern):

# write code here

if not s and not pattern:

return true

n = len(s)

m = len(pattern)

dp = [[false]*(m+1) for i in range(n+1)]

dp[-1][-1] = true

for i in range(n,-1,-1): # 注意!這裡從n開始,考慮s為空串的情況

for j in range(m-1,-1,-1):

if j < m-1 and pattern[j+1] == '*':

if i < n and (pattern[j] == s[i] or pattern[j] == '.'):

dp[i][j] = dp[i][j+2] or dp[i+1][j] # 不匹配當前字元or匹配當前字元

else:

dp[i][j] = dp[i][j+2]

else:

if i < n and (pattern[j] == s[i] or pattern[j] == '.'):

dp[i][j] = dp[i+1][j+1]

return dp[0][0]

劍指offer 正規表示式匹配

請實現乙個函式用來匹配包括 和 的正規表示式。模式中的字元 表示任意乙個字元,而 表示它前面的字元可以出現任意次 包含0次 在本題中,匹配是指字串的所有字元匹配整個模式。例如,字串 aaa 與模式 a.a 和 abaca 匹配,但是與 aa.a 和 aba 均不匹配 由於只涉及兩種正規表示式的匹配,...

劍指Offer 正規表示式匹配

題目 請實現乙個函式用來匹配包括 和 的正規表示式。模式中的字元 表示任意乙個字元,而 表示它前面的字元可以出現任意次 包含0次 在本題中,匹配是指字串的所有字元匹配整個模式。例如,字串 aaa 與模式 a.a 和 ab ac a 匹配,但是與 aa.a 和 ab a 均不匹配 實現 class s...

劍指offer 正規表示式匹配

題目 請實現乙個函式用來匹配包括 和 的正規表示式。模式中的字元 表示任意乙個字元,而 表示它前面的字元可以出現任意次 包含0次 在本題中,匹配是指字串的所有字元匹配整個模式。例如,字串 aaa 與模式 a.a 和 ab ac a 匹配,但是與 aa.a 和 ab a 均不匹配.分析 觀察模式串中第...