1. 程式人生 > 實用技巧 >go-micro中的釋出訂閱Broker分析

go-micro中的釋出訂閱Broker分析

#include <iostream>
#include <string>
using namespace std;
//獲取next陣列
int* getNext(string T)
{
    int len = T.size();   //獲取T的長度
    int* next = new int[len];    // 宣告next陣列
    int j = 0;    // T字尾下標
    int k = -1;   // T字首下標
    next[0] = -1;
    while (j < len-1)
    {
        if (k == -1 || T[j] == T[k])           //
k==-1時,短路 { j++; k++; next[j] = k; } else{ k = next[k]; //前後綴失配,進行回溯 } } return next; } // KMP演算法,在 S 中找到 T 第一次出現的位置
int KMP(string S, string T) // S為主串,T為模式串 { int* next = getNext(T); int i = 0; // S下標 int j = 0; // T下標 int s_len = S.size(); int t_len = T.size(); while (i < s_len && j < t_len) { if (j == -1 || S[i] == T[j]) //T 的第一個字元不匹配或S[i] == T[j] { i
++; j++; } else{ j = next[j]; // 當前字元匹配失敗,進行跳轉 } } if (j == t_len){ return i - j; // 匹配成功 } return -1; } int main() { string S = "bcabcdababcdabcdabde"; string T = "abcdabd"; int num = KMP(S, T); cout << num <<endl; return 0; }