s0010
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Sainnhe Park 2022-11-03 14:57:32 +08:00
parent b39d62e895
commit 914c04c9c5
3 changed files with 75 additions and 0 deletions

View File

@ -0,0 +1,14 @@
#ifndef S0010_REGULAR_EXPRESSION_MATCHING
#define S0010_REGULAR_EXPRESSION_MATCHING
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool isMatch(string s, string p);
};
#endif

View File

@ -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<vector<int>> f(m + 1, vector<int>(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];
}

View File

@ -0,0 +1,24 @@
#include "s0010_regular_expression_matching.hpp"
#include <gtest/gtest.h>
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));
}