leetcode: Regular Expression Matching

来源:互联网 发布:做淘宝刷好评要交钱吗? 编辑:程序博客网 时间:2024/06/06 04:37

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

对于S[i]和P[j]:

如果P[j+1]!='*',S[i] == P[j]=>匹配下一位(i+1, j+1),S[i]!=P[j]=>匹配失败;

如果P[j+1]=='*',S[i]==P[j]=>匹配下一位(i+1, j+2)或者(i, j+2),S[i]!=P[j]=>匹配下一位(i,j+2)。

匹配成功的条件为S[i]=='\0' && P[j]=='\0'。

class Solution {public:    bool isMatch(string s, string p) {        /*vector<vector<bool> > dp(s.size() + 1, vector<bool>(p.size() + 1, false));        dp[0][0] = true;        for( int i = 1; i <= p.size(); ++i)            dp[0][i] = '*' == p[i-1] && i > 1 && dp[0][i-2];        for( int i = 1; i <= s.size(); ++i){            for( int j = 1; j <= p.size(); ++j){                    if(p[j-1] != '*')                        dp[i][j] = dp[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.');                    else                        dp[i][j] = dp[i-1][j] && j > 1 && (s[i-1] == p[j-2] || p[j-2] == '.') || dp[i][j-1] || j > 1 && dp[i][j-2];            }        }        return dp[s.size()][p.size()];*/        if(p == "*")            return true;        return core(s, p, 0, 0);    }    bool core(string s, string p, int i, int j){        if( j >= p.size())            return i >= s.size();        if( p[j+1] != '*'){            if(s[i] == p[j] || (p[j] == '.' && i < s.size()))                return core(s, p, i+1, j+1);            else                return false;        }        else{            while(s[i] == p[j] || (p[j] == '.' && i < s.size())){                if( core(s, p, i, j + 2))                    return true;                ++i;            }            return core(s, p, i, j + 2);        }    }};


0 0