Skip to content

Commit

Permalink
feat: add z function
Browse files Browse the repository at this point in the history
  • Loading branch information
STommydx committed Aug 31, 2024
1 parent eb15efc commit 916aaee
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
20 changes: 20 additions & 0 deletions string.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,26 @@ std::vector<int> prefix_function(R &&s) {
return pi;
}

template <std::ranges::random_access_range R>
requires std::ranges::sized_range<R>
std::vector<int> z_function(R &&s) {
std::vector<int> z(std::ranges::size(s));
int l = 0, r = 0;
for (int i = 1; i < std::ranges::ssize(s); i++) {
if (i < r) {
z[i] = std::min(r - i, z[i - l]);
}
while (i + z[i] < std::ranges::ssize(s) && s[z[i]] == s[i + z[i]]) {
z[i]++;
}
if (i + z[i] > r) {
l = i;
r = i + z[i];
}
}
return z;
}

std::vector<int> kmp(const std::string &str, const std::string &pattern) {
std::vector<int> pi = prefix_function(pattern + "#" + str);
std::vector<int> result;
Expand Down
8 changes: 8 additions & 0 deletions string_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ TEST_CASE("prefix function behaves as expected", "[string]") {
REQUIRE(prefix_function(v) == std::vector<int>{0, 1, 0, 0, 0, 0, 1, 2, 3});
}

TEST_CASE("z function behaves as expected", "[string]") {
REQUIRE(z_function("baobaba") == std::vector<int>{0, 0, 0, 2, 0, 2, 0, 0});
std::string s = "baobaba";
REQUIRE(z_function(s) == std::vector<int>{0, 0, 0, 2, 0, 2, 0});
std::vector<int> v = {2, 2, 8, 1, 5, 3, 2, 2, 8};
REQUIRE(z_function(v) == std::vector<int>{0, 1, 0, 0, 0, 0, 3, 1, 0});
}

TEST_CASE("kmp behaves as expected", "[string]") {
std::string s = "ababa";
std::string p = "aba";
Expand Down

0 comments on commit 916aaee

Please sign in to comment.