diff --git a/CMakeLists.txt b/CMakeLists.txt index eb3e90c..fe98f1d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,4 +9,6 @@ add_executable(data_structure_homework main.cpp problem2.cpp problem2.h problem3.cpp - problem3.h) + problem3.h + problem4.cpp + problem4.h) diff --git a/main.cpp b/main.cpp index 2cde612..502deaa 100644 --- a/main.cpp +++ b/main.cpp @@ -4,6 +4,7 @@ #include "problem1.h" #include "problem2.h" #include "problem3.h" +#include "problem4.h" int main() { problem_1(); @@ -11,4 +12,6 @@ int main() { problem_2(); std::cout << "------------------------" << std::endl; problem_3(); + std::cout << "------------------------" << std::endl; + problem_4(); } diff --git a/problem4.cpp b/problem4.cpp new file mode 100644 index 0000000..e24e814 --- /dev/null +++ b/problem4.cpp @@ -0,0 +1,41 @@ +// +// Created by grtsinry43 on 5/8/25. +// + +#include "problem4.h" + +#include +#include +#include + +std::vector naive_string_match(const std::string &text, const std::string &pattern) { + std::vector positions; + int text_length = text.size(); + int pattern_length = pattern.size(); + + for (int i = 0; i <= text_length - pattern_length; ++i) { + int j = 0; + while (j < pattern_length && text[i + j] == pattern[j]) { + ++j; + } + if (j == pattern_length) { + positions.push_back(i); // 记录匹配的起始位置 + } + } + return positions; +} + +int problem_4() { + std::string text = "ababcabcacbab"; + std::string pattern = "abc"; + + std::vector positions = naive_string_match(text, pattern); + + std::cout << "Pattern found at positions: "; + for (int pos : positions) { + std::cout << pos << " "; + } + std::cout << std::endl; + + return 0; +} \ No newline at end of file diff --git a/problem4.h b/problem4.h new file mode 100644 index 0000000..07662d3 --- /dev/null +++ b/problem4.h @@ -0,0 +1,10 @@ +// +// Created by grtsinry43 on 5/8/25. +// + +#ifndef PROBLEM4_H +#define PROBLEM4_H + +int problem_4(); + +#endif //PROBLEM4_H