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,仍是能够匹配任意的字符。因此‘.*’确实是万能的。应该没有理解错误吧。 而后这题,考虑了好久,都没有想到好的思路,不得不用递归。express

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

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

提交尝试好屡次把 if (*p == '\0') return *s == '\0'; 忽略。由于是递归的,因此不能没有。这里的'.'不能对应‘\0’less

也能够参考这位同窗的。学习

相关文章
相关标签/搜索