Add problem4 implementation and update CMakeLists and main.cpp
This commit is contained in:
parent
f01e47c076
commit
1b0488d635
@ -9,4 +9,6 @@ add_executable(data_structure_homework main.cpp
|
|||||||
problem2.cpp
|
problem2.cpp
|
||||||
problem2.h
|
problem2.h
|
||||||
problem3.cpp
|
problem3.cpp
|
||||||
problem3.h)
|
problem3.h
|
||||||
|
problem4.cpp
|
||||||
|
problem4.h)
|
||||||
|
|||||||
3
main.cpp
3
main.cpp
@ -4,6 +4,7 @@
|
|||||||
#include "problem1.h"
|
#include "problem1.h"
|
||||||
#include "problem2.h"
|
#include "problem2.h"
|
||||||
#include "problem3.h"
|
#include "problem3.h"
|
||||||
|
#include "problem4.h"
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
problem_1();
|
problem_1();
|
||||||
@ -11,4 +12,6 @@ int main() {
|
|||||||
problem_2();
|
problem_2();
|
||||||
std::cout << "------------------------" << std::endl;
|
std::cout << "------------------------" << std::endl;
|
||||||
problem_3();
|
problem_3();
|
||||||
|
std::cout << "------------------------" << std::endl;
|
||||||
|
problem_4();
|
||||||
}
|
}
|
||||||
|
|||||||
41
problem4.cpp
Normal file
41
problem4.cpp
Normal 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
10
problem4.h
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
//
|
||||||
|
// Created by grtsinry43 on 5/8/25.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef PROBLEM4_H
|
||||||
|
#define PROBLEM4_H
|
||||||
|
|
||||||
|
int problem_4();
|
||||||
|
|
||||||
|
#endif //PROBLEM4_H
|
||||||
Loading…
x
Reference in New Issue
Block a user