Leetcode: Regular Expression Matching

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   
分析:此题仍可归类为细节题,虽然看似复杂,但仔细分析发现其中逻辑后,还是比较容易实现。所以遇到感觉上比较复杂的题,要认真分析可能出现的情况,然后将不同的情况归类,从而实现由繁到简。
我们首先对p中当前第一个字符后面的字符进行讨论。假设p指向当前字符,那么p+1的字符有两种可能,一是'*',另一种不是'*'(感觉像废话)。
1. 如果P+1不为‘*’,如果*p == *s或者*p == '.'并且*s != '\0',那么p+1, s+1后的两个字符串还有可能match; 否则,两个字符串不match。
2. 如果p+1为'*'。这里我们可以细分为三种情况讨论:
  1)如果*p != *s,那么我们需要判断isMatch(s, p+2),因为'*'这里表示p指向的字符个数为0.
  2)如果*p == *s, 那么我们需要考虑'*'表示一个或多个*p的情况。
  3)如果*p == '.' && *s != '\0',那么我们需要考虑'*'表示一个字符到'*'表示*s后所有字符的情况。
有了上述的分析,我们可以通过递归的方式实现isMatch,代码如下:
class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if(*p == '\0') return *s == '\0';
        
        if(*(p+1) != '*'){//if next is not '*'
            if(*p == *s || *p == '.' && *s != '\0')
                return isMatch(s+1, p+1);
            else return false;
        }else{
            while(*p == *s || *p == '.' && *s != '\0'){
                if(isMatch(s,p+2))
                    return true;
                s++;
            }
            return isMatch(s, p+2);
        }
    }
};

 


  

posted on 2014-12-03 22:14  Ryan-Xing  阅读(149)  评论(0编辑  收藏  举报