码迷,mamicode.com
首页 > 其他好文 > 详细

Regular Expression Matching

时间:2014-07-12 13:17:10      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   art   cti   

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

思路:对于字符串匹配,s[i]和p[j].此题的关键就在于p[j+1]是否为‘*‘.递归思路解题。

如果p[j+1]!=‘*‘,s[i]==p[j],则匹配下一位(i+1,j+1),如果s[i]!=p[j],匹配失败

如果p[j+1]==‘*‘,s[i]==p[j],则匹配(i,j+2)或者(i+1,j+2),如果s[i]!=p[j],则匹配(i,j+2)

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if(*p==\0)
            return *s==\0;
        if(*(p+1)!=*)
        {
            while(*s!=\0 && (*s==*p || *p==.))
            {
                return isMatch(s+1,p+1);
            }
        }
        else
        {
            while(*s!=\0 && (*s==*p||*p==.))
            {
                if(isMatch(s,p+2))
                    return true;
                s++;
            }
            return isMatch(s,p+2);
        }
        return false;
    }
};

 使用动态规划解题,思路和上述很相似,dp[j][i]表示s[0..j]和p[0...j]是否匹配;

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        int slen=strlen(s);
    int plen=strlen(p);
    vector<vector<bool> > dp(slen+1,vector<bool>(plen+1,false));
    dp[0][0]=true;
    for(int i=1;i<=plen;++i)
    {
        if(p[i]!=*)
        {
            for(int j=1;j<=slen;++j)
            {
                dp[j][i]=(dp[j-1][i-1] && (s[j-1]==p[i-1]||p[i-1]==.));
            }
        }
        else
        {
            dp[0][i]=dp[0][i+1]=dp[0][i-1];
            for(int j=1;j<=slen;++j)
            {
                dp[j][i]=dp[j][i+1]=(dp[j-1][i]&&(s[j-1]==p[i-1] || p[i-1]==.)||dp[j][i-1]);
            }
            ++i;
        }
    }
    return dp[slen][plen];
    }
};

 

Regular Expression Matching,布布扣,bubuko.com

Regular Expression Matching

标签:style   blog   color   使用   art   cti   

原文地址:http://www.cnblogs.com/awy-blog/p/3811616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!