LeetCode 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
思路一:最先想到的是直接进行处理,处理各种可能出现的状况。这样实现起来编程难度较大,逻辑清晰也蛮难的,很难一次性bug free


思路二:通过分析不难发现,判别是否匹配实际上是一种状态的转换,然后就联想到了动态规划。使用动态规划之前,我们需要理清所求解问题的动态方程:

初始条件:dp[0][0] = true; dp[i][0] = false, i < s.length+1;dp[0][i] = i> 1 && p[i-1] == '*' && p[0][i-2];

动态方程:if p[j-1] == '*' then p[i][j] = p[i][j-2]&&(p[j-2] == '.' || p[i-2] == s[i-1]) && p[i-1][j];

 else then p[i][j] = p[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.');

代码如下:

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


动态规划真是个好东西

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值