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; } } }