Sword finger Offer: regular expression matching (C++/Python)

Keywords: Python

Title Description

Please implement a function to match regular expressions including '.' and '*'. The character '.' in the pattern indicates any character, while '*' indicates that the character before it can appear any number of times (including 0 times) In this problem, matching means that all characters of a string match the whole pattern. For example, the string "a a a" matches the patterns "a.a" and "ab*ac*a", but not "aa.a" and "ab*a"

Solving problems

When the second character in the pattern is not *, if the character corresponding to the string matches the character corresponding to the pattern (the same or.. in the pattern), the string and the pattern move one character backward respectively, and then match the remaining string and pattern. Otherwise, return False directly

When the second character in the pattern is *, ① the pattern moves two characters backward directly, ② the character corresponding to the string matches the character corresponding to the pattern, and the character moves backward one, and the pattern can remain unchanged or move backward two characters

C++ version

class Solution {
public:
    bool match(char* str, char* pattern)
    {
        if(str == nullptr || pattern == nullptr)
            return false;
        return matchCore(str,pattern);
    }
    bool matchCore(char* str, char* pattern){
        if(*str == '\0' && *pattern == '\0')
            return true;
        if(*str != '\0' && *pattern == '\0')
            return false;
        if(*(pattern + 1) == '*'){
            if(*pattern == *str || (*str != '\0' && *pattern == '.'))
                return matchCore(str+1, pattern+2) || matchCore(str+1, pattern) || matchCore(str, pattern+2);
            else
                return matchCore(str, pattern+2);
        }
        if(*str == *pattern || (*pattern == '.' && *str != '\0'))
            return matchCore(str+1, pattern+1);
        return false;
    }
};

Python version

class Solution:
    # s, pattern are strings
    def match(self, s, pattern):
        # write code here
        return self.matchCore(s, pattern, 0, 0)
    def matchCore(self, s, pattern, i, j):
        if i == len(s) and j == len(pattern):
            return True
        if j >= len(pattern) or i > len(s):
            return False
        if j < len(pattern)-1 and pattern[j+1] == '*':
            if i == len(s) or pattern[j] == s[i] or pattern[j] == '.':
                return self.matchCore(s,pattern,i,j+2) or self.matchCore(s,pattern,i+1,j) or self.matchCore(s,pattern,i+1,j+2)
            else:
                return self.matchCore(s,pattern,i,j+2)
        if i == len(s) or pattern[j] == s[i] or pattern[j] == '.':
            return self.matchCore(s,pattern,i+1,j+1)
        return False

 

Posted by PunjabHaker on Sun, 17 Nov 2019 13:54:48 -0800