diff --git a/include/s0010_regular_expression_matching.hpp b/include/s0010_regular_expression_matching.hpp new file mode 100644 index 0000000..157c74a --- /dev/null +++ b/include/s0010_regular_expression_matching.hpp @@ -0,0 +1,14 @@ +#ifndef S0010_REGULAR_EXPRESSION_MATCHING +#define S0010_REGULAR_EXPRESSION_MATCHING + +#include +#include + +using namespace std; + +class Solution { + public: + bool isMatch(string s, string p); +}; + +#endif diff --git a/src/s0010_regular_expression_matching.cpp b/src/s0010_regular_expression_matching.cpp new file mode 100644 index 0000000..27e0820 --- /dev/null +++ b/src/s0010_regular_expression_matching.cpp @@ -0,0 +1,37 @@ +#include "s0010_regular_expression_matching.hpp" + +// 动态规划 +// 当前匹配成功 == 之前匹配成功 && 当前字符匹配成功 + +bool Solution::isMatch(string s, string p) { + int m = s.size(); + int n = p.size(); + + auto matches = [&](int i, int j) { + if (i == 0) { + return false; + } + if (p[j - 1] == '.') { + return true; + } + return s[i - 1] == p[j - 1]; + }; + + vector> f(m + 1, vector(n + 1)); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p[j - 1] == '*') { + f[i][j] |= f[i][j - 2]; + if (matches(i, j - 1)) { + f[i][j] |= f[i - 1][j]; + } + } else { + if (matches(i, j)) { + f[i][j] |= f[i - 1][j - 1]; + } + } + } + } + return f[m][n]; +} diff --git a/tests/s0010_regular_expression_matching.cpp b/tests/s0010_regular_expression_matching.cpp new file mode 100644 index 0000000..d10bda4 --- /dev/null +++ b/tests/s0010_regular_expression_matching.cpp @@ -0,0 +1,24 @@ +#include "s0010_regular_expression_matching.hpp" + +#include + +TEST(Problem10, Case1) { + string s{"aa"}; + string p{"a"}; + Solution solution; + EXPECT_FALSE(solution.isMatch(s, p)); +} + +TEST(Problem10, Case2) { + string s{"aa"}; + string p{"a*"}; + Solution solution; + EXPECT_TRUE(solution.isMatch(s, p)); +} + +TEST(Problem10, Case3) { + string s{"ab"}; + string p{".*"}; + Solution solution; + EXPECT_TRUE(solution.isMatch(s, p)); +}