字符串匹配——BM算法
BM算法通过Java语言实现。
public class BFMatching { public static void main(String[] args) { long startTime; long endTime; long durationTime; startTime = System.nanoTime(); BM(); endTime = System.nanoTime(); durationTime = endTime - startTime; System.out.println(durationTime); } public static void BM() { String BM_S = "ababcabcacbab"; String BM_T = "abcac"; int BMSLength = BM_S.length(); //主串长度 int BMTLength = BM_T.length(); //子串长度 int i = BMTLength - 1; while (i <= BMSLength) { for (int j = BMTLength - 1; j >= 0; ) { if (BM_T.charAt(j) == BM_S.charAt(i)) { System.out.println(BM_T.charAt(j) + "==" + BM_S.charAt(i)); if (j == 0) { System.out.println("匹配成功!"); return; } j--; i--; } else if (BM_T.charAt(j) != BM_S.charAt(i)) { i = i + Dist(BM_S.charAt(i)); j = BMTLength - 1; } } } } public static int Dist(char c) { int dist = 0; if (c == 'a') { dist = 1; } else if (c == 'b') { dist = 3; } else if (c == 'c') { dist = 5; } return dist; } }
运行结果:
c==c
c==c
a==a
c==c
b==b
a==a
匹配成功!
655247
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。