[LeetCode] Regular Expression matching

来源:互联网 发布:淘宝店招素材图 编辑:程序博客网 时间:2024/05/17 03:12

'.' 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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true

Refer to: http://leetcode.com/2011/09/regular-expression-matching.html

The recursion mainly breaks down elegantly to the following two cases:

  1. If the next character of p is NOT ‘*’, then it must match the current character of s. Continue pattern matching with the next character of both s and p.
  2. If the next character of p is ‘*’, then we do a brute force exhaustive matching of 0, 1, or more repeats of current character of p… Until we could not match any more characters.

You would need to consider the base case carefully too. That would be left as an exercise to the reader. :)


class Solution {public:    bool isMatch(const char *s, const char *p) {        // Note: The Solution object is instantiated only once and is reused by each test case.            assert(s&&p); //exit when s and p points to NULL        //base case:        if(*p=='\0') return *s=='\0';                if(*(p+1) != '\*')        {            //a strict matching            assert( *p!='\*' ); //the start of p cannot be *            if(*s==*p || (*p=='.' && *s!='\0') )                return isMatch(s+1,p+1);            else                return false;        }        else{            //recursively match different number(1~until *s and *p failed to match) of *p in s            while( *s==*p || (*p=='.' && *s!='\0') )            {                if(isMatch(s,p+2)) return true; //p+2 points to the next character after '*'                s++;            }        }        //fail to find a match with *, it means that in s, the number of "*p" is 0        return isMatch(s,p+2);    }};


原创粉丝点击