• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
10. Regular Expression Matching *HARD*

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

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

 

2.

bool isMatch(string s, string p) {
    int ls = s.length(), lp = p.length(), i, j;
    if(p == "")
        return s == "";
    if(1 == lp || p[1] != '*')
    {
        if(s == "" || (p[0] != '.' && s[0] != p[0]))
            return false;
        return isMatch(s.substr(1), p.substr(1));
    }
    //p[1] == '*'
    for(i = -1; i < ls && (-1 == i || '.' == p[0] || s[i] == p[0]); i++ )
    {
        if(isMatch(s.substr(i+1), p.substr(2)))
            return true;
    }
}

 

posted on 2016-03-07 10:07  ArgenBarbie  阅读(187)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3