算法總結大全(正在日更)

https://blog.csdn.net/starstar1992/article/details/54913261 KMP(樸素的算法 樸素的解釋)
https://blog.csdn.net/u013200703/article/details/48402901 exkmp 算法
https://blog.csdn.net/HelloZEX/article/details/80780953 最快最簡單的排序——桶排序 解釋很形象

//【KMP】【模板】最精簡的
#include
#include
using namespace std;

const int N = 1000002;
int next[N];
string S, T;
int slen, tlen;

void getNext()
{
int j, k;
j = 0; k = -1; next[0] = -1;
while(j < tlen)
if(k == -1 || T[j] == T[k])
next[++j] = ++k;
else
k = next[k];

}
/*
返回模式串T在主串S中首次出現的位置
返回的位置是從0開始的。
*/
int KMP_Index()
{
int i = 0, j = 0;
getNext();

while(i < slen && j < tlen)
{
    if(j == -1 || S[i] == T[j])
    {
        i++; j++;
    }
    else
        j = next[j];
}
if(j == tlen)
    return i - tlen;
else
    return -1;

}
/*
返回模式串在主串S中出現的次數
*/
int KMP_Count()
{
int ans = 0;
int i, j = 0;

if(slen == 1 && tlen == 1)
{
    if(S[0] == T[0])
        return 1;
    else
        return 0;
}
getNext();
for(i = 0; i < slen; i++)
{
    while(j > 0 && S[i] != T[j])
        j = next[j];
    if(S[i] == T[j])
        j++;
    if(j == tlen)
    {
        ans++;
        j = next[j];
    }
}
return ans;

}
int main()
{

int i, cc;
    getline(cin,T);
    getline(cin,S);
    for(int i=0;i<S.length();i++)
    if (S[i]!=' '&&S[i]>='A'&&S[i]<='Z')
    {
        S[i]=S[i]-'A'+'a';
    }
    for(int i=0;i<T.length();i++)
    if (T[i]!=' '&&T[i]>='A'&&T[i]<='Z')
    {
        T[i]=T[i]-'A'+'a';
    }
    slen = S.length();
    tlen = T.length();
    cout<<S<<'\n'<<T<<endl;
    if(KMP_Index()==-1) cout<<-1<<endl;
    else cout<<KMP_Count()<<" "<<KMP_Index()<<endl;
return 0;

}

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