1. 程式人生 > >字串匹配之Brute-Force演算法

字串匹配之Brute-Force演算法

簡單模式匹配演算法(BF演算法)

//匹配成功返回str2在str1中shou首次出現的位置

	public static int BForce(String str1, String str2) {
		int i = 0, j = 0;
		while (i < str1.length() && j < str2.length()) {
			if (str1.charAt(i) == str2.charAt(j)) {// 繼續匹配下個字元
				i++;
				j++;
			} else { // 回溯
				i = i - j + 1;
				j = 0; // 從頭匹配
			}
		}

		if (j >= str2.length())
			return (i - str2.length() + 1);
		else
			return 0;

	}