[LeetCode]Regular Expression Matching

class Solution {
//1. If the next character of p is NOT '*', then it must match the current character of s. 
//Continue pattern matching with the next character of both s and p.
//2. If the next character of p is '*', then we do a brute force exhaustive matching of 0, 1, or 
//more repeats of current character of p... Until we could not match any more characters.
//recursion
public:
	bool isMatch(const char *s, const char *p) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function    
		if (*p == '\0') return *s == '\0';
		if ( *(p+1) != '*')
			return ( (*s == *p) || (*p == '.' && *s != '\0') ) && isMatch(s+1, p+1);

		//if *(p+1) is '*', and *s == *p
		while ( (*s == *p) || (*p == '.' && *s != '\0') )
		{
			if( isMatch(s, p+2) ) return true;//pass zero 
			s++;//pass as more as possible
		}
		return isMatch(s, p+2);
	}
};

second time

class Solution {
//tabulation DP based
public:
    bool isMatch(const char *s, const char *p) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function    
        int len1 = 0;
        for(const char* q = s; *q != '\0' && q != NULL; ++q) len1++;
        int len2 = 0;
        for(const char* q = p; *q != '\0' && q != NULL; ++q) len2++;
        
        vector<vector<bool> > f(len1+1, vector<bool>(len2+1, false));
        f[0][0] = true;
        for(int i = 0; i <= len1; ++i)
        {
            char preChar = '\0';
            int preIdx = 0;
            for(int j = 1; j <= len2; ++j)
            {
                if(i >= 1 && (p[j-1] == '.' || s[i-1] == p[j-1])) f[i][j] = f[i-1][j-1];
                else if(p[j-1] == '*')
                {
                    if(i >= 1 && (preChar == s[i-1] || preChar == '.')) f[i][j] = f[i-1][j] || f[i][j-1];
                    f[i][j] = f[i][j] || f[i][preIdx];
                    //f[i-1][j] = f[i-1][j] || f[i-1][preIdx];
                }
                if(p[j-1] != '*') preChar = p[j-1], preIdx = j-1;
            }
        }        
        
        return f[len1][len2];
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值