Public classKMP {Private Char[] Source = {' A ', ' B ', ' C ', ' B ', ' C ', ' A ', ' B ', ' A ', ' B ', ' d ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' A ', ' B ', ' C ', ' A ', ' B ', ' A ', ' B ', ' d ', A}; Private Char[] target = {' A ', ' B ', ' C ', ' A ', ' B ', ' A ', ' B ', ' d '}; Private int[] Getnextarray (Char[] target) { int[] ret =New int[Target.length]; ret[0] = 0; for(inti = 1; i < target.length; i++) { intoffset = ret[i-1]; while(Offset > 0) { if(Target[i] = =Target[offset]) {Ret[i]= offset + 1; Break; } Else{offset=Ret[offset]; } } if(offset = = 0 && Target[i] = = Target[0]) {Ret[i]= 1; } } returnret; } Private intIndexOf (int[] Next) { intOffset = 0; inti = 0; while(I < target.length && Offset <source.length) {if(Target[i] = =Source[offset]) {i++; Offset++; } Else if(i = = 0) {offset++; } Else{i= I-1 < 0? 0:next[i-1]; } } returnoffset; } Public Static voidMain (string[] args) {KMP k=NewKMP (); Longnow =System.currenttimemillis (); for(inti = 0; i < 1000000; i++) { int[] ret =K.getnextarray (K.target); K.indexof (ret); } System.out.println (System.currenttimemillis ()-Now ); } }
With the understanding of the KMP algorithm, with Java implementation, the result and Java comes with the string indexof ratio, performance is 10 times times worse ...