1 原理
參考 《大話資料結構》第5章 串 的第5.7小節 : KMP模式比對演算法
2 java代碼
KMP.java
package leaning.string.KMP;public class KMP {public static int indexKMP(String source, String target,int pos) {/* i 用於主串source當前位置下標值,若pos不為1 則從pos位置開始匹配 */int i = pos ; /* j 用於子串 target中當前位置下標值 */int j = 1 ;/*定義一組next數組*/int[] next = new int[IntArrayLength.length]; /*對target進行分析,得到next數組*/next = NextUtil.getNext(target);// 將source,target字串變為字元數組char[] sourceChar = KMPStringUtil.stringToChar(source);char[] targetChar = KMPStringUtil.stringToChar(target);//若i小於source長度並且target小於target長度,執行迴圈while(i <=source.length() && j <= target.length() ){if(j==0 || sourceChar[i] == targetChar[j] ){++i;++j;}else{j = next[j] ;}}if( j > target.length() ){return i - target.length();}else{return 0;}}public static void main(String args[]) {String source = "asdkfjslkfjwejdklfjew8odklfjsdlkfjslkdj";String target = "w8odkl";int pos = 0;int p = KMP.indexKMP(source, target, pos);System.out.println("在位置 " +p + "完全符合");}}
NextUtil.java
package leaning.string.KMP;public class NextUtil {/** * * 得到next數組 * */public static int[] getNext( String targetStr) { if(targetStr==null) return null; char[] targetModify = KMPStringUtil.stringToChar(targetStr); // 將targetStr字串改為字元數組 int length = targetStr.length(); // 得到next數組 int i,j; i = 1 ; j = 0 ; int next[] = new int[IntArrayLength.length]; while( i < length){ if(j == 0 || targetModify[i] == targetModify[j]){ // targetModify[i]表示尾碼單個字元, targetModify[j]表示首碼的單個字元 ++i; ++j; next[i] = j ; }else{ j = next[j]; // 若字元不同,則 j 進行回溯 } } return next;} public static void main(String args[]){String targetStr = "ababaaaba" ;int next[] = NextUtil.getNext(targetStr);for(int i = 0 ; i < next.length ; i++){System.out.print(next[i] + " ");}}}
IntArrayLength.java
package leaning.string.KMP;public class IntArrayLength { public static int length = 255;}
KMPStringUtil.java
package leaning.string.KMP;public class KMPStringUtil { public static char[] stringToChar(String source){ /** * 對source進行改造,使其第一位為一個預留位置 * source = a b c d e f g h * targetModify = '' a b c d e f g h * * */ char[] targetModify = new char[source.length()+1]; int length = source.length() ; for(int i = 0 ; i < source.length() ; i++){ targetModify[i+1] = source.charAt(i); }return targetModify;} }
3 運行結果
運行 KMP.java 得到下面結果