Regular Expression Matching

来源:互联网 发布:淘宝 卖东西 编辑:程序博客网 时间:2024/06/07 00:46
题目:

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
若p[0] == '\0' ,则判断s[0] == '\0' 是则返回true 否则返回false
若p[1] == '*' 若p[0] == '.' 或者 s[0] == p[0]  则可以选择重复多次匹配s[0]直至不可重复为止,或者一次也不重复若p[1] != '*' 若p[0] == '.' 或者 s[0] == p[0]  则s和p都进一位进行匹配,否则返回false
class Solution {public:    bool isMatch(string s, string p) {        if(p[0] == '\0') return s[0] == '\0';                if(p[1] == '*')        {            while((s[0] != '\0' && p[0] == '.') || s[0] == p[0])            {                if(isMatch(s, p.substr(2, p.length() - 2))) return true;                s = s.substr(1, s.length() - 1);            }                        return isMatch(s, p.substr(2, p.length() - 2));        }        else        {            if((s[0] != '\0' && p[0] == '.') || s[0] == p[0])                return isMatch(s.substr(1, s.length() - 1), p.substr(1, p.length() - 1));        }                return false;    }};
0 0
原创粉丝点击