剑指offer---正则表达式匹配

题目:正则表达式匹配

要求:请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

class Solution {
public:
    bool match(char* str, char* pattern)
    {
    
    }
};

解题代码:

 1 class Solution {
 2 public:
 3     bool match(char* str, char* pattern) {
 4         if(str == nullptr || pattern == nullptr)
 5             return false;
 6 
 7         return matchCore(str, pattern);
 8     }
 9 private:
10     bool matchCore(char* str, char* pattern){
11         // char ch_str= *str;
12         // char ch_pattern = *pattern;
13         // cout<<ch_str<<' '<<ch_pattern<<endl;
14         if(*str == '' && *pattern == '')
15             return true;
16 
17         if(*str != '' && *pattern == '')
18             return false;
19 
20         // 下一个字符是*通配符的情况,以 abc*de 为例
21         if(*(pattern + 1) == '*'){
22             if(*pattern == *str || (*pattern =='.' && *str != ''))
23                         // c重复一次  abcde
24                 return matchCore(str + 1, pattern + 2)
25                         // c重复多次  abccccde
26                     || matchCore(str + 1, pattern)
27                         // c出现0次   abde
28                     || matchCore(str, pattern + 2);
29             else
30                         // c出现0次   abde
31                 return matchCore(str, pattern + 2);
32         }
33 
34         if(*str == *pattern || (*pattern == '.' && *str != ''))
35             return matchCore(str + 1, pattern + 1);
36         return false;
37     }
38 };
原文地址:https://www.cnblogs.com/iwangzhengchao/p/9862930.html