leetcode第十题--Regular Expression Matching

Problem: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") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true

就是正则表达式,可以百度一下先学习什么事正则表达式。*号是表示前面一个字符出现零次或者多次。例如 zo*能和z匹配是因为此处*表示前面的字符o出现零次,所以和z匹配,同理,zo*还可以和zo或者zoo,zoooo,zooooooooo等等匹配。点‘.’是通配符,匹配任意一个单字符。那么点星‘.*’就可以匹配任意多个字符,因为*表示前面的任意多个重复。所以就是任意多个‘.’的重复,而‘.’又是任意匹配,所以就是任意组合都可以。第一个点匹配a第二个点并不是只能匹配a,还是可以匹配任意的字符。所以‘.*’确实是万能的。应该没有理解错误吧。 然后这题,考虑了很久,都没有想到好的思路,不得不用递归。

class Solution {
public:
bool isMatch(const char *s, const char *p)
{
    if(s == NULL || p == NULL)
        return false;
    if (*p == '')
        return *s == '';

    if (*(p + 1) == '*')
    {
        while(*s == *p || *p == '.' && *s != '')
        {
            if (isMatch(s, p + 2))
                return true;
            s++;
        }
        return isMatch(s, p + 2);
    }
    else if (*s == *p || *p == '.'&&*s!='')
        return isMatch(s + 1, p + 1);
    return false;
}
};

提交尝试好多次把 if (*p == '') return *s == ''; 忽略。因为是递归的,所以不能没有。这里的'.'不能对应‘’

也可以参考这位同学的。

原文地址:https://www.cnblogs.com/higerzhang/p/4023437.html