Skip to content

Commit 9cd8759

Browse files
Update Regular_Expression_Matching.cpp
1 parent b62291c commit 9cd8759

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

Regular Expression Matching/Regular_Expression_Matching.cpp

+28-1
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,31 @@ class Solution
4141
}
4242
return memo[i][j];
4343
}
44-
};
44+
};
45+
46+
// 非递归的版本
47+
// 动态规划 memo[i][j]代表(从右往左)长度为j的p能否匹配长度为i的s
48+
49+
class Solution
50+
{
51+
public:
52+
bool isMatch(string s, string p)
53+
{
54+
vector<vector<bool>> memo(s.length() + 1, vector<bool>(p.length() + 1, false));
55+
memo[0][0] = true;
56+
57+
for (int i = 0; i <= s.size(); ++i)
58+
{
59+
for (int j = 1; j <= p.size(); ++j)
60+
{
61+
bool match = i != 0 && (s[s.length() - i] == p[p.length() - j] || p[p.length() - j] == '.') ? true : false;
62+
if (j != 1 && p[p.length() - j + 1] == '*')
63+
memo[i][j] = (j - 2 >= 0 && memo[i][j - 2]) || (match && memo[i - 1][j]);
64+
else
65+
memo[i][j] = match && memo[i - 1][j - 1];
66+
}
67+
}
68+
69+
return memo[s.size()][p.size()];
70+
}
71+
};

0 commit comments

Comments
 (0)