[Leetcode]10.RegularExpression Matching

题目:10.RegularExpression 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

 题目大意:从p中找到可以匹配s的字符串,如果能找到则返回true,否则返回false

其中:

        ‘.’匹配任意的单个字符

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

思路如下:

1*s字符串结束,要求*p也结束或者间隔‘*’则完成匹配;

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

(3)s和p指向的字符串没有结束时,*(p+1)字符为'*',则*p字符可以匹配*s字符串中从0开始任意多个等于*p的字符,然后递归到*(s+i+1)字符串与*(p+2)字符串的比较;

(4s和p指向的字符串没有结束时,*(p+1)字符不为'*',则只需比较*s字符与*p字符,若(相等或者*p==.)则递归到*(s+1)字符串与*(p+1)字符串的比较;

详细的代码如下:

class Solution {
public:
	bool isMatch(const char *s, const char *p) {

		//如果s结束了
		if (*s == 0)
		{
			if (*p == 0 || (*(p + 1) == '*' && isMatch(s, p + 2)))
				return true;
			else
				return false;
		}
		else if (*p == 0)//如果s没有结束p结束了
			return false;

		if (*(p + 1) != '*')//如果p+1不为*
		{
			if (*s == *p || *p == '.')
				return isMatch(s + 1, p + 1);//匹配下一个
			else
				return false;
		}
		else
		{
			if (*s != *p && *p != '.')
			{
				return isMatch(s, p + 2);
			}
			else
			{
				if (isMatch(s, p + 2))
					return true;

				int i = 0;
				//*p字符可以匹配*s字符串中从0开始任意多个等于*p的元素
				while (*(s + i) == *p || *p == '.')
				{
					if (isMatch(s + i + 1, p + 2))
						return true;
					if (*(s + i + 1) == 0)
						break;
					i++;
				}
				return false;
			}
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值