標籤: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演算法實現字串匹配