Packagecom.trs.utils; Public classKmpstr {/** In the KMP algorithm, the most difficult to find is the next function, how to understand the next function is a problem, especially k=next[k], here * need to point out that when P[i]!=p[j], we only by backtracking will be the value of K gradually reduced, seemingly similar and use the idea of dynamic planning Refer to the online Nanyi teacher's blog to explain the very detailed*/ Private Static int[] GetNext (String t) {int[] Next =New int[T.length ()]; next[0] = 1; intj = 0; intK =-1; while(J < T.length ()-1) { if(k = =-1 | | T.charat (j) = =T.charat (k)) {J++; K++; NEXT[J]=K; } Else{k=Next[k]; } } for(intI:next) {System.out.print (i+ ":"); } System.out.println (); returnNext; } Public Static intKmpstrindex (string s, String T,int[] Next) { inti = 0; intj = 0; while(I < S.length () && J <t.length ()) { if(j = =-1 | | S.charat (i) = =T.charat (j)) {i++; J++; } Else { //I do not change, J backj =Next[j]; } if(J = =t.length ()) { returnIJ; } } return-1; }}
View Code
Java implementation of KMP algorithm