菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
141
0

leetcode第十题--Regular Expression Matching

原创
05/13 14:22
阅读数 9963

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 == '\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’

也可以参考这位同学的。

发表评论

0/200
141 点赞
0 评论
收藏