程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> C++實現KMP模式匹配算法

C++實現KMP模式匹配算法

編輯:關於C++

 

#include
#include
#include

using namespace std; 

void Next(const string & pat,vector & next)
{
	next.resize(pat.length());
	if(pat.length() == 0) 
		return;
	next[0] = -1;
	
	for(size_t pos = 1; pos < pat.length(); ++pos)
	{
		size_t sublen = pos-1;
		while(sublen >= 0)
		{	
			if(pat.substr(0, sublen) == pat.substr(pos-sublen+1, sublen))
				break;
			--sublen;
		}	
		next[pos] = sublen;
	}
	return;
}

int main(void)
{
	string str1, str2;
	while(cin >> str1 >> str2) {
		vector next;
		Next(str2, next);

		vector pos;

		int i = 0, j1 = 0, j2 = 0;
		while(j1 < str1.length()) 
		{
			j2 = j1 - i;
			if(j2 >= str2.length()) {
				// found
				pos.push_back(i);
				// move on;
				int delta = str2.length();
				i = i + delta;
				j1 = max(i,j1);	
			}
			else if(str1[j1] == str2[j2]) {
				++j1;
			}
			else { 	// str1[j1] != str2[j2];
				int delta = j2 - next[j2];
				i = i + delta;
				j1 = max(i,j1);
			}
		}

		//output.
		cout << str1.length():  << str1.length() << endl;
		cout << str2.length():  << str2.length() << endl;
		cout << str1 from pos:  << endl;
		for(int i = 0; i < pos.size(); ++i) 
			cout << [ << (i+1) << ]:  << str1.substr(pos[i], string::npos) << endl;
		cout << str2:  << str2 << endl;
	}
	return 0;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved