[leetcode]Regular Expression Matching

 

此题有难度。一开始是用循环往前p和s贪心来做,代码已经很复杂,但处理依然有(大)错。如 aaab配a*ab 和 babc配.*c的情况无法处理。看了网上的资料后才认定这种情况必须要全面回溯匹配,这种情况下最适合的就是递归了。默默的写程序,中间有漏过*s!=0的判断,但几次修改后居然通过了,小激动。

参考:http://discuss.leetcode.com/questions/175/regular-expression-matching

class Solution {
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) != '*')
		{
			if (*s != 0 && (*p == *s || *p == '.')) return isMatch(s+1, p+1);
			else return false;
		}
		else
		{
			// *s == *p
			while (*s != 0 && (*s == *p || *p == '.'))
			{
				if (isMatch(s, p+2)) return true;
				s++;
			}
			return (isMatch(s, p+2));
		}
    }
};

Another:

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if (*p == '\0') {
            return *s == '\0';
        }
        if (*s != '\0' && (*s == *p || *p == '.')) {
            if (*(p+1) == '*') {
                return isMatch(s, p+2) || isMatch(s+1, p);
            } else {
                return isMatch(s+1, p+1);
            }
        }
        if (*(p+1) == '*') {
            return isMatch(s, p+2);
        } else {
            return false;
        }
    }
};

  

 

转载于:https://www.cnblogs.com/lautsie/p/3217563.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值