package org.loda.string; import org.junit.Assert; /** * * @ClassName: NaiveStringMatcher * @Description: 樸素字符串查找 * * text:abcabaabcabac pattern:abaa * * @author minjun * @date 2015年7月7日 下午4:02:14 * */ public class NaiveStringMatcher { public static void main(String[] args) throws Exception { // 原始文本 String text = "abcabaabcabac"; // 查找的模式 String pattern = "abaa"; // 模式在文本中第一次出現的位置 int index = // indexOf(text, pattern); search(text, pattern); System.out.println(index); } /** * * @Title: indexOf * @Description: 隱式回退 * @param @param text * @param @param pattern * @param @return 設定文件 * @return int 返回類型 * @throws */ private static int indexOf(String text, String pattern) { Assert.assertNotNull(text); Assert.assertNotNull(pattern); int tLen = text.length(); int pLen = pattern.length(); if (tLen < pLen) return -1; // 每次都往右邊偏移一位來比較text和pattern for (int i = 0; i < tLen - pLen + 1; i++) { int j; // 最多進行pLen輪比較 for (j = 0; j < pLen; j++) { // 若是發現不相等的立刻中止比較 if (text.charAt(i + j) != pattern.charAt(j)) { break; } } // 比較完成以後,若是比較了pLen次,說明執行了完整的比較而且找到了pattern的位置i if (j == pLen) { return i; } } // 若是仍是沒有找到pattern的位置,說明在text不存在pattern return -1; } /** * * @Title: search * @Description: 顯示回退 * @param @param text * @param @param pattern * @param @return 設定文件 * @return int 返回類型 * @throws */ private static int search(String text, String pattern) { Assert.assertNotNull(text); Assert.assertNotNull(pattern); int tLen = text.length(); int pLen = pattern.length(); if (tLen < pLen) return -1; int i, j; for (i = 0, j = 0; i < tLen && j < pLen; i++) { if (text.charAt(i) == pattern.charAt(j)) { //若是匹配,則i++,j++,進行後面字符的比較 j++; } else { //若是發現不匹配的,將i顯示回退到剛開始比較的位置,並將j回退爲0 i -= j; j = 0; } } //若是發現j=pLen,說明比較完成而且匹配成功。可是匹配完成後,i在最後一個元素的後一位,因此字符串匹配的起始位置爲i-pLen if (j == pLen) { return i-pLen; } else { return -1; } } }