加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[LeetCode] Regular Expression Matching [6]

发布时间:2020-12-14 01:45:08 所属栏目:百科 来源:网络整理
导读:题目: 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 pro

题目:

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

原题地址

解题思路

设计一个支持‘.' 和 '*' 的正则表达式匹配算法。
这个题复杂的地方在于对于 '*' 的处理,这个符号在正则表达式中被称为贪婪型的量词。这个量词在实际匹配过程中也是尽可能多的匹配直到词尾或者不匹配成功才结束,然后如果其后面还有没有匹配的,则回退到合适的位置,然后才进行下一个匹配。正则表达式中的匹配优先与回溯大概也就是这个意思。关于正则表达式这方面的知识,有兴趣可以读读《精通正则表达式》的第4章表达式的匹配原理。
回到本题,正因为 '*'的特殊性,我们在分类的时候选择根据 '*' 来进行,分类后其子问题也是一个正则表达式匹配的问题,所以这可以使用递归来做。下面来看看代码,代码中有注释说明匹配的类型:

代码实现:

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) != '*'){
            if(*p==*s || (*p=='.' && *s!=''))
                return isMatch(s+1,p+1);
            return false;
        }
        else{
            //s="aaaabbbb",p="a.*b"
            while(*p==*s || (*p=='.' && *s!='')){
                if(isMatch(s,p+2))
                    return true;
                ++s;
            }
            //s="ab",p="aa*b"
            return isMatch(s,p+2);
        }
    }
};
如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号: swalge 或者扫描下方二维码关注我

(转载文章请注明出处:http://blog.csdn.net/swagle/article/details/28407559 )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读