Add problem4 implementation and update CMakeLists and main.cpp

This commit is contained in:
grtsinry43 2025-05-08 14:03:00 +08:00
parent f01e47c076
commit 1b0488d635
Signed by: grtsinry43
GPG Key ID: F3305FB3A978C934
4 changed files with 57 additions and 1 deletions

View File

@ -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)

View File

@ -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();
}

41
problem4.cpp Normal file
View File

@ -0,0 +1,41 @@
//
// Created by grtsinry43 on 5/8/25.
//
#include "problem4.h"
#include <iostream>
#include <string>
#include <vector>
std::vector<int> naive_string_match(const std::string &text, const std::string &pattern) {
std::vector<int> 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<int> 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;
}

10
problem4.h Normal file
View File

@ -0,0 +1,10 @@
//
// Created by grtsinry43 on 5/8/25.
//
#ifndef PROBLEM4_H
#define PROBLEM4_H
int problem_4();
#endif //PROBLEM4_H