10. Regular Expression Matching

10. Regular Expression Matching

Description

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

思路:

我们采取回溯法来解决这个问题,首先我们定义函数match(i, j)表示即将匹配i位置和j位置,那么接下来分两种情况处理,一种是p[j]后跟了一个,另外一种是不跟,对于后面有的我们枚举匹配的个数。 对于不跟的直接比较就行。
如果匹配到了i=s.length() j=p.length()那么就是true. 否则如果仅仅是j=p.length(),那么是false. i=s.length()可能匹配也可能不匹配。

class Solution {
public:
    bool match(string &s, int i, string &p, int j) {
        if(i==s.length() && j==p.length()) return true;
        else if(j==p.length()) return false;
        
        bool res = false;
        if(j+1<p.length() && p[j+1]=='*') {
            res = res || match(s, i, p, j+2);
            int num = s.length() - i;
            for(int a=1; a<=num&&(s[i+a-1]==p[j]||p[j]=='.'); a++) {
                res = res || match(s, i+a, p, j+2);
            }
        }else if(i<s.length() && (s[i]==p[j] || p[j]=='.'))
            res = res || match(s, i+1, p, j+1);
        return res;
    }
    bool isMatch(string s, string p) {
        return match(s, 0, p, 0);
    }
};
原文地址:https://www.cnblogs.com/xingxing1024/p/7518380.html