Leetcode 10. Regular Expression Matching

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

 

题目大意:

'*'代表 前一个字符重复0或若干次。

题目思路:

 

  1. P[i][j] = P[i - 1][j - 1], if p[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
  2. P[i][j] = P[i][j - 2], if p[j - 1] == '*'
  3. P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'), if p[j - 1] == '*'

 

AC代码:

Java:

 

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

C:

1、考虑特殊情况即*s字符串或者*p字符串结束。

(1)*s字符串结束,要求*p也结束或者间隔‘*’ (例如*p="a*b*c*……"),否则无法匹配

(2)*s字符串未结束,而*p字符串结束,则无法匹配

2、*s字符串与*p字符串均未结束

(1)*(p+1)字符不为'*',则只需比较*s字符与*p字符,若相等则递归到*(s+1)字符串与*(p+1)字符串的比较,否则无法匹配。

(2)*(p+1)字符为'*',则*p字符可以匹配*s字符串中从0开始任意多(记为i)等于*p的字符,然后递归到*(s+i+1)字符串与*(p+2)字符串的比较

 bool isMatch(char* s, char* p) {

   if (s == NULL || p == NULL) return false;
    if (*p == '\0') return *s == '\0';
    // ".*" matches "", so we can't check (*s == '\0') here.
    if (*(p + 1) == '*')
    {
        // Here *p != '\0', so this condition equals with
        // (*s != '\0' && (*p == '.' || *s == *p)).
        while ((*s != '\0' && *p == '.') || *s == *p)
        {
            if (isMatch(s, p + 2)) return true;
            ++s;
        }
        
        return isMatch(s, p + 2);
    }
    else if ((*s != '\0' && *p == '.') || *s == *p)
    {
        return isMatch(s + 1, p + 1);
    }
    
    return false;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值