This commit is contained in:
parent
b39d62e895
commit
914c04c9c5
14
include/s0010_regular_expression_matching.hpp
Normal file
14
include/s0010_regular_expression_matching.hpp
Normal 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
|
37
src/s0010_regular_expression_matching.cpp
Normal file
37
src/s0010_regular_expression_matching.cpp
Normal 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];
|
||||
}
|
24
tests/s0010_regular_expression_matching.cpp
Normal file
24
tests/s0010_regular_expression_matching.cpp
Normal 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));
|
||||
}
|
Loading…
Reference in New Issue
Block a user