字符串匹配——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

 

 

 

 

你可能感兴趣的:(Algorithm)