【數據結構】---kmp算法

#include <iostream>
#include <cstring>
using namespace std;
int getIndexOf(string str1, string str2){
	int len1 = str1.length();
	int len2 = str2.length();
	int i1 = 0;
	int i2 = 0;
	int *next = new int [len2];
	next[0] = -1;
	next[1] = 0;
	int pos = 2;
	int cn = 0;
	while(pos < len2){
		if(str2[pos-1] == str2[cn]){
			next[pos++] = ++cn;
		}else if(cn > 0){
			cn = next[cn];
		}else{
			next[pos++] = 0;
		}
	}

	while(i1 < len1 && i2 < len2){
		if(str1[i1] == str2[i2]){
			i1++;
			i2++;
		}
		else if(next[i2] == -1){
			i1++;
		}
		else{
			i2 = next[i2];
		}
	} 
	return i2 == len2 ? i1 - i2 : -1;
}

int main(){
	string s1, s2;
	cin >> s1 >> s2;
	cout << getIndexOf(s1, s2);
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章