KMP演算法,字串匹配

來源:互聯網
上載者:User

/*<br />過了一年再學KMP,為AC自動機做準備。<br />嚴蔚敏的《資料結構》P82講的還算清楚。<br />不想學的直接拉去做模板吧,適合一個字串去匹配多個目標串。<br />*/<br />#include <stdio.h><br />#include <string.h><br />const int MaxN = 1000;<br />char a[MaxN] , b[MaxN];<br />int next[MaxN];<br />void get_next(char *s)<br />{<br />next[1] = 0;<br />int i = 1 , j = 0 , l = strlen(s --);<br />while (i < l){<br />if (j == 0 || s[i] == s[j]){<br />i ++;<br />j ++;<br />next[i] = s[i] != s[j] ? j : next[j];<br />}else{<br />j = next[j];<br />}<br />}<br />}<br />int kmp(char *a , char *b)<br />{<br />int n = strlen(a --) , m = strlen(b --);<br />int i = 0 , j = 0;<br />while (i <= n && j <= m){<br />if (j == 0 || a[i] == b[j]){<br />i ++;<br />j ++;<br />}else{<br />j = next[j];<br />}<br />}<br />return j > m ? i - m - 1 : -1;<br />}</p><p>void __test()<br />{<br />scanf("%s%s" , a , b);<br />get_next(b);<br />printf("%d/n" , kmp(a , b));<br />}<br />int main()<br />{<br />__test();<br />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.