1.简单匹配算法:
1 private int search(String source, String pattern) { 2 int i = 0; 3 int j = 0; 4 5 int length = pattern.length(); 6 int lastIndex = source.length() - length; 7 8 while (i <= lastIndex && j < length) { 9 if (source.substring(i, i + length).equals(pattern)) { 10 return i; 11 } else { 12 i++; 13 } 14 } 15 16 return -1; 17 }
2.KMP 算法学习
很重要的next[]获得方法:
1 private void getNextVal(String pattern, int[] next) { 2 // 求模式串T的next函数值并存入数组 next。 3 4 int j = 0, k = -1; 5 next[0] = -1; 6 while (j < pattern.length()) { 7 if (k == -1 || pattern.charAt(j) == pattern.charAt(k)) { 8 ++j; 9 ++k; 10 11 if (j < pattern.length() && k < pattern.length()) { 12 if (pattern.charAt(j) != pattern.charAt(k)) { 13 next[j] = k; 14 } else { 15 next[j] = next[k]; 16 } 17 } 18 19 } else { 20 k = next[k]; 21 } 22 } 23 }
进行匹配:
1 private int searchKMP(String source, String pattern) { 2 int i = 0; 3 int j = 0; 4 5 int[] next = new int[pattern.length() + 1]; 6 getNextVal(pattern, next); 7 8 while (i < source.length() && j < pattern.length()) { 9 if (source.charAt(i) == pattern.charAt(j)) { 10 i++; 11 j++; 12 } else { 13 if (next[j] != -1) { 14 j = next[j]; 15 } else { 16 j = 0; 17 i++; 18 } 19 } 20 } 21 22 if (j == pattern.length()) { 23 return i - j; 24 } else { 25 return -1; 26 } 27 }
参考:http://www.cppblog.com/oosky/archive/2006/07/06/9486.html