#include <iostream>
#include<string>
using namespace std;
void preMp(const char * x, int m, int * ps) {
int i, j;
i = 0;
j = ps[0] = -1;
//cout << ps[0]<<x<<m; //m= 2
//cout << x[i] << x[j];
while (i < m) {
while (j > -1 && x[i] != x[j])
j = ps[j];
ps[++i] = ++j;
//cout << ps[i] << i;
}
}
void MP(string p, string t) {
int m = p.length();
int n = t.length();
//cout << m << n;
if (m > n) {
cerr << "Unsuccessful match!" << endl;
return;
}
const char * x = p.c_str(); //c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
const char * y = t.c_str();
//cout << x << y; x= hk, m = 2;
int i = 0, j = 0;
int* ps = new int [m+1];
//cout << sizeof(ps);
preMp(x, m, ps);
//cout << i;// j<<ps[1];
//cout << ps[3];
while (j < n) {
while (i > -1 && x[i] != y[j])
i = ps[i];
i +=1;
j++;
//cout << i;
if (i >= m) {
cout << "Matching index found at : " << j - i +1<< endl;
}
}
}
int main()
{
void MP(string t, string p);
string p;
string t;
cout << "输入两个字符串用空格分开,判断字符串1在字符串2中起始的位置\n";
cin >> t;
cin >> p;
MP(t, p);
return 0;
}
mp基础 算法 (忽略注释)
猜你喜欢
转载自blog.csdn.net/qq_40860649/article/details/78640306
今日推荐
周排行