Regular Expression Matching

29 篇文章 0 订阅

 

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

 

从左到右扫描模式串,dp[i] 表示s[0- i]是否匹配当前p[0-j]  j表示当前匹配的p的下标。

若j= strlen(p) - 1时 dp[strlen(s)] == true与s匹配成功,dp从0下标开始,dp[0]表示空串,初试是i= 0,dp[0]=1,即空串匹配空串。

当p[i + 1] 为常规字符串是,dp[i] = dp[i - 1] && (p[i] == '.' || p[i] == s[j - 1])

当p[i +1] 为‘*’ 时,所有原来为true的下标k及k后面等于*前字符的都为true ,即能匹配p[i]。最后i指向*后面的字符继续匹配!

 

 

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if(s == NULL || p == NULL)return false;
	//	if(!(*s && *p))return false;
		int slen = strlen(s);
		while(*p == '*')p++;
		int plen = strlen(p);

		int star_count = 0;
		
		for(int i = 0; p[i]; i++)
		{
			if(p[i] == '*')star_count++;
		}
		if(slen < plen - 2 * star_count)return false;

		int *dp = new int[slen + 5];
		memset(dp, 0, sizeof(int) * (slen + 5));
		dp[0] = 1;

		for(int i = 0; i < plen; i++)
		{
			if(p[i + 1] == '*')
			{
				for(int j = 0; j <= slen; j++)
				{
					if(!dp[j])continue;

					int k;
					//dp[j] 为true 则j 和j后面匹配 *之前字母的都 为true
					for(k = j + 1; k <= slen && (p[i] == '.' || p[i] == s[k - 1]); k++)
					{
						dp[k] = 1;
						//cout <<i <<"--"<<k<<" "<<dp[k]<<endl;
					}

					//这里开始逻辑错误,因为循环会j++ 所有j = k - 1,不是j = k
					j = k - 1;
				}
			//	dp[0] = dp[0] && dp[i + 1] == '*';
				i++;
			}
			else
			{
				for(int j = slen; j >= 1; j--)
				{
					dp[j] = dp[j - 1] && (p[i] == '.' || s[j - 1] == p[i]);
					//cout <<i <<"--"<<j<<" "<<dp[j]<<endl;
				}
				//若p[i]为正常字符,则“”不能匹配p[0 - i]
				//dp[0]表示空串对当前的匹配
				dp[0] = 0;
			}
		}
		int rtv = dp[slen];
		delete[] dp;
		return rtv;

    }
};


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值