Leetcode--Backtracking(python)

10. Regular Expression Matching

Given an input string (s) and a pattern §, 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

仔細看examples,注意’*‘的兩種情況,一個是代表前一個字符重複0次(相當於忽略前一個字符),另一個是代表前一個字符重複n次,而且’*‘是不可以單獨出現的;
感覺使用遞歸比動態規劃更容易理解一些;
返回條件是p爲空的時候,子問題是對’*‘的情況的分類考慮;
可以首先考慮沒有’*'的情況,比較簡單,就判斷當前s[0]和p[0]是否匹配以及子問題是否匹配,即:

class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        if not p:
            return not s
        
        first_m = bool(s) and p[0] in {s[0], '.'}
        
        return first_m and self.isMatch(s[1:], p[1:])

加上’*‘就是考慮當p[2]==’*'的時候的兩種情況,要麼直接忽略前一個字符,要麼當前匹配,而且重複n次:

class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        if not p:
            return not s
        
        first_m = bool(s) and p[0] in {s[0], '.'}
        
        if len(p)>=2 and p[1] == '*':
            return (self.isMatch(s, p[2:])) or (first_m and self.isMatch(s[1:], p))
        
        else:
            return first_m and self.isMatch(s[1:], p[1:])
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章