29std::vector<uint64_t>
Z_function(
const std::string &pattern) {
30 uint64_t pattern_length = pattern.size();
31 std::vector<uint64_t> z(pattern_length, 0);
33 for (uint64_t i = 1, l = 0, r = 0; i < pattern_length; i++) {
35 z[i] = std::min(r - i + 1, z[i - l]);
37 while (i + z[i] < pattern_length &&
38 pattern[z[i]] == pattern[i + z[i]]) {
41 if (i + z[i] - 1 > r) {
55 const std::string &text) {
56 uint64_t text_length = text.size(), pattern_length = pattern.size();
57 std::vector<uint64_t> z =
Z_function(pattern +
'#' + text);
58 std::vector<uint64_t> matching_indexes;
60 for (uint64_t i = 0; i < text_length; i++) {
61 if (z[i + pattern_length + 1] == pattern_length) {
62 matching_indexes.push_back(i);
65 return matching_indexes;
74 std::string text1 =
"alskfjaldsabc1abc1abcbksbcdnsdabcabc";
75 std::string pattern1 =
"abc";
79 assert((matching_indexes1 == std::vector<uint64_t>{10, 14, 18, 30, 33}));
82 std::string text2 =
"greengrass";
83 std::string pattern2 =
"abc";
87 assert((matching_indexes2 == std::vector<uint64_t>{}));
90 std::string text3 =
"";
91 std::string pattern3 =
"abc";
95 assert((matching_indexes3 == std::vector<uint64_t>{}));
98 std::string text4 =
"redsand";
99 std::string pattern4 =
"";
102 std::vector<uint64_t> matching_indexes4 =
find_pat_in_text(pattern4, text4);
103 assert((matching_indexes4 == std::vector<uint64_t>{0, 1, 2, 3, 4, 5, 6}));