演算法 字串匹配演算法 暴力匹配演算法 KMP演算法

2021-10-10 08:40:28 字數 1134 閱讀 1633

如果當前字元匹配成功, 即 str1[i]==str2[j], 則 i++; j++; 繼續匹配下乙個字元

如果當前字元匹配失敗, 則 i=i-(j-1); j=0; 也就是每次匹配失敗時, i回溯, j被置為0

public static void main(string args)

/** 暴力匹配演算法*/

public static int bruteforcematch(string str1, string str2) else

}if (j == s2len) else

}}輸出:

> 下標為 15

* 通過暴力匹配演算法匹配字串會發生大量的回溯, 因此匹配速度不佳. 不推薦使用

它常用於文字串 s內查詢一 個模式串 p的出現位置. 由 donald knuth, vaughan pratt, james h. morris三人於 2023年聯合發表, 故取三人的姓氏命名

kmp演算法就是利用之前判斷過的資訊, 通過乙個 next陣列, 儲存模式串中前後最長公共子串行的長度, 每次回溯時, 通過 next陣列找到, 前面匹配過的位置, 省去了大量的計算時間

public static void main(string args)

/** 部分匹配表:

* - 首先獲取到長度較小的字串的部分匹配值*/

public static int kmpnext(string dest)

if (dest.charat(i) == dest.charat(j))

next[i] = j;

}return next;

}/** kmp搜尋演算法*/

public static int kmpsearch(string str1, string str2, int next)

if (str1.charat(i) == str2.charat(j))

if (j == str2.length())

}return -1;

}}輸出:

> [0, 0, 0, 0, 1, 2, 0]

> 下標為 15

如果您覺得有幫助,歡迎點讚哦 ~ 謝謝!!

字串暴力匹配演算法

暴力匹配演算法 如果用暴力匹配的思路,並假設現在 str1 匹配到 i位置,子串 str2 匹配到 j 位置,則有 1 如果當前字元匹配成功 即 str1 i str2 j 則i j 繼續匹配下乙個字元 2 如果失配 即 str1 i str2 j 令i i j 1 j 0 相當於每次匹配失敗時,i...

字串匹配暴力演算法

include define maxsize 100 typedef struct sqstring void strassign sqstring s,char cstr 初始化串 s.length i void destroystr sqstring s 釋放串 void strcopy sqs...

字串匹配演算法 樸素(暴力)匹配演算法的實現

字串匹配問題 假設存在原始的字串 abcabdfhfd 之後使用 r 表示,現提供另乙個匹配字串 abdf 之後使用 m 表示,請計算得出 m 字串在 r 字串中的位置 問題分析 按照常規的思維,要計算兩個字串的匹配關係,需要使用較短的匹配字串逐項對比原始字串,如果發現有字串不匹配則回到初始位置的後...