[LeetCode] Regular Expression matching

'.' 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

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);
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章