LeetCode:10 正则表达式匹配 C++

描述

实现支持 '.' 和 '*' 的正则表达式匹配。'.' 匹配任意单个字符。'*' 匹配零个或多个前面的元素。匹配应该覆盖整个输入字符串(不是部分字符串)。函数:bool isMatch(const char *s, const char *p)>例子:isMatch("aa","a") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true

分析

绝对称得上是一道难题了这里最难的是对*的处理,有三种情况

    a*完全不匹配,即需要跳过 *以及 *前面的字母;

    a* 只匹配一个字母

    a* 匹配多个有两种方法:

递归


  // 图片来自https://www.jianshu.com/p/85f3e5a9fcda

对照以上情况写就可以,其中比较难理解的情况5,是存在字母+*的情况,当*前的字母p[0]和s[0]可以匹配的时候:

    当不需要匹配这个字母和*就可以匹配的时候(比如ab c*ab),删掉p的前两个,也就是走isMatch(s,p.substr(2));

    当需要匹配的时候,就各自减掉一个,继续情况5(比如aab a*b)

动态规划

    因为具有递归性质、重叠子问题的性质,所以可以用动态规划来考虑。

dp[i][j]表示s前i个和p前j个匹配,注意这里假设字符串前面都有一个空串,dp[1][1]表示s的第一个字母和p的第一个字母匹配,而不是前两个!!

然后就可以考虑下面几种情况:

If p[j] == s[i] :  dp[i+1][j+1] = dp[i][j];
If p[j] == '.' : dp[i+1][j+1] = dp[i][j];
If p[j]== '*': 
   here are two sub conditions:
               1   if p[j-1] != s[i]: dp[i+1][j+1] = dp[i+1][j-1]  //in this case, a* only counts as empty
               2   if p[j-1] == s[i] or p[i-1] == '.':
                              dp[i+1][j+1] = dp[i][j+1]    //in this case, a* counts as multiple a 
                           or dp[i+1][j+1] = dp[i+1][j]   // in this case, a* counts as single a
                           or dp[i+1][j+1] = dp[i+1][j-1]   // in this case, a* counts as empty

代码:

递归:

bool isMatch(string s, string p) {
        int lens = s.length(), lenp = p.length();
	if (lenp == 0)return lens == 0;
	if (lenp == 1)
	{
		if (lens == 0)return false;
		if (lens != 0 && (p[0] == s[0]|| p[0]=='.'))return isMatch(s.substr(1), p.substr(1));
		else return false;
	}
	if (lenp >= 2)
	{
		if (p[1] != '*')
		{
			if (s.length() != 0 && (p[0] == s[0] || p[0] == '.'))return isMatch(s.substr(1), p.substr(1));
			else return false;
		}
		else
		{
			while (s.length() != 0 && (p[0] == s[0] || p[0] == '.'))
			{
				if (isMatch(s, p.substr(2)))return true;
				else {
					s = s.substr(1);
				}
			}
			return isMatch(s, p.substr(2));
		}
	} }


动态规划:

 bool isMatch(string s, string p) {
       int lens = s.length(), lenp = p.length();
	bool ** dp = new bool*[lens + 2];
	for (int i = 0; i < lens+2; i++)
		dp[i] = new bool[lenp + 2];

	for (int i = 0; i < lens+2; i++)
		for (int j = 0; j < lenp+2; j++)
			dp[i][j] = false;
	dp[0][0] = true;

	for (int i = 1; i < lenp; i++)
		if (p[i] == '*'&&dp[0][i - 1])
			dp[0][i + 1] = true;

	for (int i = 0; i < lens; i++)
		for (int j = 0; j < lenp; j++)
		{
			if (s[i] == p[j] || p[j] == '.')
				dp[i + 1][j + 1] = dp[i][j];
			else if (p[j] == '*')
			{
				if (p[j - 1] != s[i] && p[j - 1] != '.')
					dp[i + 1][j + 1] = dp[i + 1][j - 1];
				else
					dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]);
			}
		}


	return dp[lens][lenp];
    }

 
 



猜你喜欢

转载自blog.csdn.net/beforeeasy/article/details/79735776
今日推荐