Skip to content

Commit

Permalink
Regular Expression Matching
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 16, 2023
1 parent c2d85fc commit ac1d857
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 1 deletion.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,7 @@ add_task(reconstruct-itinerary)
add_task(recover-a-tree-from-preorder-traversal)
add_task(recover-binary-search-tree)
add_task(reducing-dishes)
add_task(regular-expression-matching)
add_task(remove-colored-pieces-if-both-neighbors-are-the-same-color)
add_task(remove-duplicate-letters)
add_task(remove-duplicates-from-sorted-array)
Expand Down
1 change: 1 addition & 0 deletions solutions/regular-expression-matching/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_regular_expression_matching test.cpp)
34 changes: 34 additions & 0 deletions solutions/regular-expression-matching/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#pragma once

#include <regex>
#include <string>

class Solution {
public:
static bool isMatch(std::string s, std::string p) {
const int n = s.size(), m = p.size();

std::vector dp(n + 1, std::vector<bool>(m + 1));
dp[0][0] = true;

for (int j = 1; j <= m; ++j) {
dp[0][j] = p[j - 1] == '*' && dp[0][j - 2];
}

for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (p[j - 1] == '*') {
if (p[j - 2] == '.' || p[j - 2] == s[i - 1]) {
dp[i][j] = dp[i][j - 2] || dp[i - 1][j];
} else {
dp[i][j] = dp[i][j - 2];
}
} else if (p[j - 1] == '.' || p[j - 1] == s[i - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}
}
}

return dp[n][m];
}
};
39 changes: 39 additions & 0 deletions solutions/regular-expression-matching/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
std::string s;
std::string p;
bool expected;
};

std::vector<TestCase> test_cases{
{
.s = "aa",
.p = "a",
.expected = false,
},
{
.s = "aa",
.p = "a*",
.expected = true,
},
{
.s = "ab",
.p = ".*",
.expected = true,
},
{
.s = "aa",
.p = "a*",
.expected = true,
},
};

for (const auto &[s, p, expected] : test_cases) {
const auto actual = Solution::isMatch(s, p);
REQUIRE(expected == actual);
}
}
2 changes: 1 addition & 1 deletion solutions/valid-number/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ TEST_CASE("VALID NUMBERS") {
}
}

TEST_CASE("Not Valid Numbers") {
TEST_CASE("NOT VALID NUMBERS") {
std::vector<std::string> not_numbers{"abc", "1a", "1e", "e3", "99e2.5",
"--6", "-+3", "95a54e53", ".", "e"};
for (const auto &not_number : not_numbers) {
Expand Down

0 comments on commit ac1d857

Please sign in to comment.