KMP-看毛片算法 c++
生活随笔
收集整理的這篇文章主要介紹了
KMP-看毛片算法 c++
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
!!!這篇文章有錯誤,日后更新,推薦立即關閉該網頁。
--2020/4/30
?
kmp算法包括兩步
1,計算next數組,即對要尋找的字符串標記值,例如abcabc,這邊有六個字符,從a開始,將每一個字符與這個字符串開頭開始匹配,第一個字符標記為0,第二個字符為b,明顯與字符串開頭a不相等,因此標記為0。第四個字符為a,與字符串開頭a相等,因此標記為1,第五個字符為b,但他前面的字符被標記為1,因此第五個字符要與第1+1個字符相比較,如果相似,則標記為前一個字符標記的值+1.
貼代碼
?
void cal_next(int *next,char tstr[100],int tlen)//這邊傳遞了next數組的地址,要標記的字符串以及用于遍歷的字符串長度; {next[0] = 0;//對第一個字符標記為0;for (int i = 1; i < tlen; i++)//遍歷,先查看前一個字符的標記值,如果為0,則將字符與第一個字符相比較,如果不為0,假設為x,則與第x+1個字符比較;{if (next[i - 1] == 0){if (tstr[i] == tstr[0])next[i] = 1;elsenext[i] = 0;}else{if (tstr[i] == tstr[next[i - 1]])next[i] = next[i - 1] + 1;elsenext[i] = 0;}} }2.進行匹配,如果匹配到目標數組中間發現后面不匹配,就訪問最后一個匹配字符的標記值,例如主串abcabbbbbb,目標串abcabc假設匹配到第二個b的時候后面不匹配了,根據之前的求next數組方法,可以得到目標串。第二個b的標記值為2,這個b在目標串位置為第5個,因此下次要移動5-2次,即移動三個單位,此時目標串的a剛好對上主串第二個a。
?
貼代碼
?
int kmp(char sstr[], char tstr[], int next[], int slen, int tlen) {int i = 0, j = 0;while (i < slen)//遍歷主串{bool flag = true;//立個flag,循環一下如果倒了,說明不匹配。while (j < tlen)//遍歷目標串{if (sstr[i] == tstr[j])//判斷是否匹配{i++;j++;continue;}else{flag = false;break;}}if (flag == true)//看flag有不有倒。return i - j + 1;else{if (j == 0)//這個if語句之前沒用,產生了bug,當j=0的時候,next[j-1]是next[-1],這時就會得到意外的值。i = i + 1;else{i = i + (j - next[j - 1]);j = 0;}}}return -1;//如果匹配失敗,則返回-1; }-------------------------------------------切割-----------------下面是完整代碼-----------------------------------------------------------
?
?
#include <iostream> #include <string> using namespace std; void cal_next(int *next,char tstr[100],int tlen) {next[0] = 0;for (int i = 1; i < tlen; i++){if (next[i - 1] == 0){if (tstr[i] == tstr[0])next[i] = 1;elsenext[i] = 0;}else{if (tstr[i] == tstr[next[i - 1]])next[i] = next[i - 1] + 1;elsenext[i] = 0;}} } int kmp(char sstr[], char tstr[], int next[], int slen, int tlen) {int i = 0, j = 0;while (i < slen){bool flag = true;while (j < tlen){if (sstr[i] == tstr[j]){i++;j++;continue;}else{flag = false;break;}}if (flag == true)return i - j + 1;else{if (j == 0)i = i + 1;else{i = i + (j - next[j - 1]);j = 0;}}}return -1; } int main() {char sstr[100], tstr[100], ch = 0;int slen, tlen;cout << "Please enter the sstr:" << endl;cin >> sstr;again:cout << "Please enter the ttstr:" << endl;cin >> tstr;slen = strlen(sstr);tlen = strlen(tstr);int next[100];cal_next(next, tstr, tlen);cout << "The next array is:";for (int i = 0; i < tlen; i++)cout << next[i];cout << endl;int situ;situ = kmp(sstr, tstr, next, slen, tlen);cout << "These two strings are matched in No." << situ << endl;goto again;system("pause");return 0; }?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的KMP-看毛片算法 c++的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 油田开采基础知识
- 下一篇: s3c2440移植MQTT