[Sword Finger Offer] _17 Regular Expression Matching

Title description

Please implement a function to match '*'the regular expression including '.' And . The character '.' In the pattern represents any character, and '*'the character before it can appear any number of times (including 0 times). In this question, matching means that all characters of the string match the entire pattern. For example, the string "aaa" matches the patterns "aa" and "ab ac a", but does not match "aa.a" and "ab * a"

Problem-solving ideas

There are two cases, see if the next character of the expression is'*'

  1. The next character of pattern is not ‘*’: this case is relatively simple and directly matches the current character. If the
    match is successful, continue to match the next one; if the match fails, directly return false. Note that the
    "matching success" here , in addition to the case where the two characters are the same, there is a case where the
    current character of the pattern is '.' And the current character of str is not '\ 0'.
  2. a next character pattern ‘*’, the slightly more complicated, because the '*' can represent 0 or more.
    All these situations are considered here:
    • When ‘*’matching 0 characters, the current character of str is unchanged, and the current character of pattern is shifted by two bits,
      skipping this ‘*’symbol;
    • When ‘*’matching one or more, the current character of str moves to the next, and the current character of pattern
      remains unchanged. (Match 1 or more here can be regarded as a case, because: when matching one,
      because str moves to the next character, and the pattern character is unchanged, it returns to the upper case a;
      when matching more than one character , Equivalent to continue to match from the next character of str)

Code

class Solution {
public:
    bool match(char* str, char* pattern)
    {
        if(*str == '\0'&& *pattern == '\0')
            return true;
        if(*str != '\0' && *pattern == '\0')
            return false;
        
        //如果表达式的下一个字符不是*
        //正常处理
        //判断当前是否相等或者只要表达式为.并且匹配的字符串不为空
        //然后返回str+,pattern+1判断下一个
        if(*(pattern+1) != '*'){
            if(*str == *pattern || *str != '\0'&& *pattern == '.')
                return match(str+1,pattern+1);
            else
                return false;
        }
        //否则下一个字符为'*'
        else{
            if(*str == *pattern || *str!= '\0' && *pattern == '.')
                return match(str,pattern+2)|| match(str+1,pattern);
            else
                return match(str,pattern+2);
        }
           
    }
};
Published 253 original articles · praised 41 · 40,000+ views

Guess you like

Origin blog.csdn.net/liuyuchen282828/article/details/104080409