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:])
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章