Skip to content

Commit 9be0d55

Browse files
author
applewjg
committed
dp solution for regular matching
1 parent 75281a1 commit 9be0d55

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

RegularExpressionMatching.h

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
/*
22
Author: Annie Kim, [email protected]
3+
Co-author: King, [email protected]
34
Date: May 26, 2013
4-
Update: Aug 19, 2013
5+
Update: Oct 26, 2014
56
Problem: Regular Expression Matching
67
Difficulty: Hard
78
Source: http://leetcode.com/onlinejudge#question_10
@@ -22,6 +23,7 @@
2223
isMatch("aab", "c*a*b") ? true
2324
2425
Solution: Both of the two solutions are from http://leetcode.com/2011/09/regular-expression-matching.html .
26+
Solution 3: DP.
2527
*/
2628

2729
class Solution {
@@ -53,4 +55,23 @@ class Solution {
5355
else
5456
return *(p+1) == '*' && isMatch(s, p+2);
5557
}
58+
59+
bool isMatch_3(const char *s, const char *p) {
60+
int l1 = strlen(s), l2 = strlen(p), k;
61+
char ch1, ch2;
62+
vector<vector<bool> > f(l1 + 1, vector<bool>(l2 + 1,false));
63+
f[0][0] = true;
64+
for (int i = 2; i <= l2; i ++)
65+
if (*(p + i - 1) == '*') f[0][i] = f[0][i - 2];
66+
for (int i = 1; i <= l1; i ++)
67+
for (int j = 1; j <= l2; j ++) {
68+
ch1 = *(s + i - 1); ch2 = *(p + j - 1);
69+
if (ch2 != '*') f[i][j] = f[i - 1][j - 1] && (ch1 == ch2 || ch2 == '.');
70+
else {
71+
f[i][j] = f[i][j - 2];
72+
if (*(s + i - 1) == *(p + j - 2) || *(p + j - 2) == '.') f[i][j] = f[i][j] | f[i - 1][j];
73+
}
74+
}
75+
return f[l1][l2];
76+
}
5677
};

0 commit comments

Comments
 (0)