String text = "我爱北京天安门,天安门在北京,北京城在北方"; String pattern = "北京";
search(pattern, text); search2(pattern, text); }
privatestaticvoidsearch(String pat, String txt){ int m = pat.length(); int n = txt.length();
for (int s = 0; s < n - m + 1; s++) { for (int i = 0; i < m; i++) { if (txt.charAt(s + i) != pat.charAt(i)) { break; } if (i == m - 1) { System.out.println("有效偏移量:" + s); } } } }
/** * 另一种实现,显式回退 */ privatestaticvoidsearch2(String pat, String txt){ int m = pat.length(); int n = txt.length();
// 这里s不再是偏移量而是文本中已经匹配的最后一个字符 for (int s = 0, i = 0; s < n && i < m; s++) { if (txt.charAt(s) == pat.charAt(i)) { if (i == m - 1) { System.out.println("有效偏移量:" + (s - i)); continue; } i++; } else { s = s - i; i = 0; } } } }