您的位置:首页 > 其它

字符串匹配——BM算法

2015-05-06 13:54 176 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: