KMP演算法實現字串匹配

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   ar   for   div   

#include<stdio.h>#include<string>#include<iostream>using namespace std;int main(){    string str,p;    cin>>str>>p;    int n=str.length();    int m=p.length();        //compute prefix function    int pre[100];    pre[0]=-1;    int k=-1;    for(int j=1;j<m;j++)    {       while(k!=-1&&p[k+1]!=p[j])//這裡剛開始用if,現在用while,這是為什麼呢? j往後退,尋找新的可能性       {          k=pre[k];       }       if(p[k+1]==p[j])       {          k=k+1;       }       pre[j]=k;    }    for(int i=0;i<m;i++)    {       printf("%d ",pre[i]);    }    int j=-1;    for(int s=0;s<n;s++)    {        while(j!=-1&&p[j+1]!=str[s])           j=pre[j];        if(p[j+1]==str[s])           j++;        if(j==m-1)//當j到達m-1時候,字串就已經匹配成功了        {           printf("Match!\n");           //break;           j=-1;//multi match ,如果允許已經匹配的字串重疊呢?        }    }     printf("\n");    getchar();    getchar();    return 0;} 

Question: 字串A是否是字串B的字串?

A: KMP演算法

資料: http://www.ituring.com.cn/article/59881 講得很透徹

http://www.matrix67.com/blog/archives/115 原創講解

http://mindhacks.cn/2011/07/10/the-importance-of-knowing-why-part3/ 為什麼學演算法這麼難?

KMP演算法實現字串匹配

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.