10. Regular Expression Matching

来源:互联网 发布:知行英语综合教程下载 编辑:程序博客网 时间:2024/06/15 17:34
'.' 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
bool isMatch(string s, string p) {        if(p.empty())            return s.empty();        if('*'==p[1])            return  isMatch(s,p.substr(2))||!s.empty()&&(s[0]==p[0]||'.'==p[0])&&isMatch(s.substr(1),p);        else            return !s.empty()&&(s[0]==p[0]||'.'==p[0])&&isMatch(s.substr(1),p.substr(1));    }

bool isMatch(string s, string p) {        int m = s.length(),n = p.length();        int dp[m+1][n+1]={false};        dp[0][0]=true;        for(int i = 0; i < m+1; i++) {            for(int j = 1; j < n+1; j++) {                if(p[j-1] != '*') {                    dp[i][j] = i > 0 && dp[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.');                }                else {                    dp[i][j] = dp[i][j-2] || (i > 0 && dp[i-1][j] && (s[i-1] == p[j-2] || p[j-2] == '.'));                 }            }        }        return dp[m][n];    }


原创粉丝点击