main.cpp

来自「一个我的数据结构解题集合」· C++ 代码 · 共 61 行

CPP
61
字号
#include <iostream>
#include <string>
#include "IoUtils.h"
#include "KMPSearch.h"
using namespace std;


/* 演示调用search函数在str中搜索ptn的过程
 */
typedef Vector<int> (*SearchFunc)(const string&, const string&);
void showSearch(const string& str, const string& ptn, SearchFunc search) {
	cout << "模式匹配的位置: " << endl;

	Vector<int> result = search(str, ptn);
	for (int i = 0; i < result.size(); ++i) {
		cout << " " << result[i];
	}
	cout << "\n位置表示: " << endl;
	cout << str << "\n";
	for (int j = 0, lastpos = 0; j < result.size(); ++j) {
		int offset = result[j] - lastpos - 1;
		for (int k = 0; k < offset; ++k) {
			cout << " ";
		}
		cout << "^";
		lastpos = result[j];
	}
	cout << "\n" << endl;
} // showSearch(const string&, const string&, SearchFunc)


int main() {
	const string ptn = "aabbaab";

	cout << "在主串中搜索所有模式P = \"" << ptn << "\", \n"
		 << "包括重叠及不重叠2种种情况"
		 << endl;
	try {
		cout << "请输入主串: ";
		string str = getString();

		// 重叠情况下的匹配
		cout << "重叠情况下: " << endl;
		showSearch(str, ptn, KmpSearchAll);
		
		// 无重叠情况下的匹配
		cout << "无重叠情况下: " << endl;
		showSearch(str, ptn, KmpSearchAllNoOverlap);

	} catch (const std::exception& e) {
		cerr << "捕捉到异常!" << endl;
		cerr << e.what() << endl;
		pause();
		return 1;
	}

	pause();
	return 0;

} // main()

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?