-
条件:无 -
题目:无 -
原理:无 -
代码:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <map>
#include <queue>
#include <stack>
#include <deque>
#include <string>
#include <cstring>
#include <cmath>
#include <fstream>
#include <ctime>
#include <climits>
using namespace std;
class Solver {
public:
Solver() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
public:
void SaveCpp(string name) const {
fstream input;
fstream output;
input.open("moota.cpp", ios::in);
output.open(name.c_str(), ios::out);
char c = 'O';
while (!input.eof()) {
input.get(c);
output << c;
}
input.close();
output.close();
}
protected:
virtual void BeginPlay() {
};
virtual void Playing() {
};
virtual void EndPlay() {
};
public:
void Play() {
BeginPlay();
Playing();
EndPlay();
}
};
class SpecialSolver : public Solver {
public:
typedef long long int lld;
typedef unsigned long long int ulld;
static const lld MAX = static_cast<lld>(1e4);
static const lld INF = static_cast<lld>(1e18);
private:
string text, pattern;
int kmp[MAX];
private:
void Normal() {
const int aSize = text.size() - 1;
const int bSize = pattern.size() - 1;
for (int i = 1; i <= aSize; ++i) {
int k = i;
for (int j = 1; j <= bSize; ++j) {
if (text[k] != pattern[j]) {
break;
}
else {
++k;
if (j == bSize) {
cout << i << " ";
}
}
}
}
}
void GetKMP() {
kmp[0] = 0;
kmp[1] = 0;
int len = 0;
const int aSize = pattern.size() - 1;
for (int i = 2; i <= aSize; ++i) {
while (len > 0 && pattern[i] != pattern[len + 1]) {
len = kmp[len];
}
if (pattern[i] == pattern[len + 1]) {
++len;
kmp[i] = len;
}
}
}
void DoKMP() {
int len = 0;
const int aSize = text.size() - 1;
const int bSize = pattern.size() - 1;
for (int i = 1; i <= aSize; ++i) {
while (len > 0 && text[i] != pattern[len + 1]) {
len = kmp[len];
}
if (text[i] == pattern[len + 1]) {
++len;
if (len == bSize) {
cout << i - bSize + 1 << " ";
len = kmp[len];
}
}
}
}
protected:
virtual void BeginPlay() override {
Solver::BeginPlay();
cin >> text >> pattern;
text = " " + text;
pattern = " " + pattern;
};
virtual void Playing() override {
Solver::Playing();
cout << "\n朴素匹配:";
Normal();
cout << "\nKMP匹配:";
GetKMP();
DoKMP();
};
virtual void EndPlay() override {
Solver::EndPlay();
};
};
SpecialSolver specialSolver;
int main() {
specialSolver.Play();
}
|