10. Regular Expression Matching leetcode Python 2016 new Season

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).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true


















This problem can be solved with O(n^2) time and space algorithm
1. letter matching
2. letter match with * case
3. letter match with . case
class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        length_s =  len(s)
        length_p = len(p)
        dp = [[False for _ in range(length_p + 1)] for _ in range(length_s + 1)]
        dp[0][0] = True
        for column in range(1, length_p + 1):
            if p[column - 1] == '*' and column >= 2:
                dp[0][column] = dp[0][column - 2]
        for row in range(1, length_s + 1):
            for column in range(1, length_p + 1):
                if p[column - 1] == '.':
                    dp[row][column] = dp[row - 1][column - 1]
                elif p[column - 1] == '*':                                            # aa *a      aa .*
                    dp[row][column] = dp[row][column - 1] or dp[row][column - 2] or (dp[row - 1][column] and (s[row - 1] == p[column - 2] or p[column - 2] == '.'))
                else:
                    dp[row][column] = s[row - 1] == p[column - 1] and dp[row - 1][column - 1]
        return dp[-1][-1]
            


你可能感兴趣的:(10. Regular Expression Matching leetcode Python 2016 new Season)