KMP算法

  KMP算法是一種改進的字符串匹配算法。KMP算法的關鍵是利用匹配失敗後的信息,儘可能減小模式串與主串的匹配次數以達到快速匹配的目的。具體實現就是實現一個next()函數,函數自己包含了模式串的局部匹配信息。算法

  next()函數的做用,就是在模式串中,找出最長的相同前綴,造成一張跳轉表。函數

  跳轉表的用途是,當目標串target中的某個子部target[m...m+(i-1)]與pattern串的前i個字符pattern[1...i]相匹配時,若是target[m+i]與pattern[i+1]匹配失敗,程序不會像樸素匹配算法那樣,將pattern[1]與target[m+1]對其,而後由target[m+1]向後逐一進行匹配,而是會將模式串向後移動i+1 - next[i+1]個字符,使得pattern[next[i+1]]與target[m+i]對齊,而後再由target[m+i]向後與依次執行匹配。spa

public static int[] getNext(String b) {
    int len = b.length();
    int j = 0;
    int next[] = new int[len + 1];

    next[0] = next[1] = 0;

    for (int i = 1; i < len; i++) {
        while (j > 0 && b.charAt(i) != b.charAt(j))
            j = next[j];
        if (b.charAt(i) == b.charAt(j))
            j++;
        next[i + 1] = j;
    }
    return next;
}
相關文章
相關標籤/搜索