cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/2a5ef2f50c64

时间限制:1秒 空间限制:32768K

题目描述

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

我的代码

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)||((*pattern=='.')&&(*str!='\0')))
                return matchCore(str+1,pattern) || matchCore(str,pattern+2);
            else
                return matchCore(str,pattern+2);
        }
        else{
            if((*str==*pattern)||((*pattern=='.')&&(*str!='\0')))
                return matchCore(str+1,pattern+1);
            else
                return false;
        }
    }
};

运行时间:4ms
占用内存:460k

posted on 2019-05-07 13:09  cherrychenlee  阅读(150)  评论(0编辑  收藏  举报