Leetcode 10 正則表達(dá)式匹配問(wèn)題

10. Regular Expression Matching

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

Note:

s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: "." means "zero or more () of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

正則表達(dá)式匹配,想偷懶的話,直接調(diào)用python的re庫(kù)

import re
class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        return re.fullmatch(p, s) != None

比較正規(guī)的方法是用動(dòng)態(tài)規(guī)劃的方法

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        ls=len(s)
        lp=len(p)
        dp = [[True if not j else not ls for j in range(ls+1)] for i in range(lp+1)]
        s=' '+s
        p=' '+p
        for i in range(1, lp+1):
            ast = p[i] == '*'#注此處i-1代表第i個(gè)
            dp[i][0] = ast and dp[i-2][0]
            for j in range(1, ls+1):
                dp[i][j] = ast and dp[i-2][j] or p[i-ast] in ('.', s[j]) and dp[i-1+ast][j-1]
                   
        return dp[lp][ls]

分析一下算法思路
其中遞推項(xiàng)dp[i][j]表示p的前i個(gè)字符與s中前j個(gè)字符組成的表示式是否匹配。dp[0][0]恒為T(mén)rue。
對(duì)p和s做1個(gè)偏移調(diào)整

對(duì)于p的前i個(gè)和s的前j個(gè)字符串
需考慮2種情況
㈠當(dāng)p[i]='*'時(shí),dp[i][j]為真有兩種情況:
(1)當(dāng)dp[i-2][j]為真時(shí),利用p[i]='*',可將p[i-1]消去,因此dp[i][j]仍為真,
(2)當(dāng)dp[i][j-1]為真,且p[i]='*',則可知s[j-1]一定和p[i-2]或p[i-1]相等
①當(dāng)s[j-1]==p[i-2],若s[j]==p[i-1](p[i-1]等于'.'也成立),則可以令p[i]的'*'為重復(fù)1次,正好匹配;
②當(dāng)s[j-1]==p[i-1],若s[j]==p[i-1](p[i-1]等于'.'也成立),則可以令p[i]的'*'為重復(fù)2次,正好匹配

㈡當(dāng)p[i]!='*'時(shí),dp[i][j]為真只有一種情況,dp[i-1][j-1]為真且s[j]==p[i](p[i]等于'.'也成立)。

則可以列出下列遞推式

dp[i][j]=\begin{cases} dp[i-2][j] \ \ ||\ \ (p[i-1]∈\{'.',s[j]\}\ \ \&\& \ \ dp[i][j-1]) & p[i]=='*' \\ p[i]∈\{'.',s[j]\} \ \ \&\& \ \ dp[i-1][j-1] & p[i]!='*' \\ \end{cases}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容