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

leetcode系列(34)Regular Expression Matching 正则表达式匹配

发布时间:2020-12-14 00:57:54 所属栏目:百科 来源:网络整理
导读:Regular Expression Matching Implement regular expression matching withsupport for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the precedingelement. The matching should cover the entire input string (not parti

Regular Expression Matching


Implement regular expression matching withsupport for '.' and '*'.

'.' Matches any single character.

'*' Matches zero or more of the precedingelement.

The matching should cover the entireinput 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



这题很多corner case需要考虑,也是看了leetcode开发者的这篇文章(http://articles.leetcode.com/2011/09/regular-expression-matching.html)恍然大悟的,由于'.'和'*'的特殊性,用贪心会有bug,文章里面详细描述了几个case。作者指出了两点:

1. If the next character of pis NOT '*',then it must match the current charactor of s. Continue patternmatching with the next charactor of both s and p.

2.If the next character of p is '*',then we do a brute forceexhuastive matching of 0,1,or more repeats current charactor of p... Until wecould not match any more charactors.

C++代码如下(由于Python字符串的特性就懒得给python代码了)

class Solution {
public:
    bool isMatch(string s,string p) {
        return _is_match(s.c_str(),p.c_str());
    }
    
private:
    bool _is_match(const char* s,const char* p) {
        if (*p == '') {
            return *s == '';
        } 
        
        if (*(p + 1) != '*') {
            return ((*s == *p) || (*s != '' && *p == '.')) && _is_match(s + 1,p + 1);
        } else {
            while ((*s == *p) || (*s != '' && *p == '.')) {
                if (_is_match(s,p + 2)) {
                    return true;
                } 
                ++s;
            }
            return _is_match(s,p + 2);
        }
    }
};

(编辑:李大同)

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

    推荐文章
      热点阅读