Regular Expression Matching

原创 2017年01月03日 14:59:44
/**
* f[i][j]: if s[0..i-1] matches p[0..j-1]
* if p[j - 1] != '*'
*      f[i][j] = f[i - 1][j - 1] && s[i - 1] == p[j - 1]
* if p[j - 1] == '*', denote p[j - 2] with x
*      f[i][j] is true iff any of the following is true
*      1) "x*" repeats 0 time and matches empty: f[i][j - 2]
*      2) "x*" repeats >= 1 times and matches "x*x": s[i - 1] == x && f[i - 1][j]
* '.' matches any single character
*/
class Solution {
public:
	bool isMatch(string s, string p) {
		int m = s.length(), n = p.length();
		vector<vector<bool> > dp(m + 1, vector<bool>(n + 1, false));
		dp[0][0] = true;

		for (int i = 0; i <= m; i++)
		{
			for (int j = 1; j <= n; j++)
			{
				if (p[j - 1] == '*')
					dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]);
				else
					dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
				
			}
		}
		return dp[m][n];
	}
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode 10.Regular Expression Matching(正则表达式匹配) 解题思路和方法

Regular Expression Matching Implement regular expression matching with support for '.' and '*'. ...

LeetCode之10 --- Regular Expression Matching

题目:   , Implement regular expression matching with support for '.' and '*'. '.' Matches any sin...

leetcode 10. Regular Expression Matching

leetcode 10. Regular Expression Matching 只有两种特殊字符*和. 动态规划DPempty text与empty pattern是match的用状态表T[i +...

[LeetCode] Regular Expression Matching 解题报告

[题目] mplement regular expression matching with support for ‘.’ and ‘*’. ‘.’ Matches any single ch...

leetcode -- Regular Expression Matching -- dp 重点

https://leetcode.com/problems/regular-expression-matching/trick: 如果有两个str list, 考虑用2D dp[i][j]思路1 递归...

LeetCode Regular Expression Matching 极品代码赏析

这个条件很容易忽略,也是最重要的条件了,因为这个相当于*可以把它的前缀字母”吃掉“ 所以也是为什么我们需要“往前看”,看到pattern字符串后一位,假设这个字符串为const char *p; 那...

Regular Expression Matching -- LeetCode

原题链接: http://oj.leetcode.com/problems/regular-expression-matching/  这个题目比较常见,但是难度还是比较大的。我们先来看看brute ...

leetcode 10 Regular Expression Matching

Regular Expression Matching Total Accepted: 51566 Total Submissions: 249926 Implement regul...

LeetCode Regular Expression Matching

Description: Implement regular expression matching with support for '.' and '*'. '.' Matches any s...

[Leetcode]10. Regular Expression Matching @python

题目Implement regular expression matching with support for ‘.’ and ‘*’.‘.’ Matches any single characte...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)