Public classMain1 {StaticString S1 = "ABCD"; StaticString s2 = "ABCE"; Public Static voidMain (string[] args) {//TODO auto-generated Method Stub /** String Similarity * Concept: * for two strings A and B, change the string A to B through basic additions or deletions, or change B to a, * the minimum step used in the process of change is called "Editing distance" */System.out.println (LD ()); } Public Static intLD () {intA[][] =New int[S1.length () +1] [S2.length () +1]; for(inti = 0; I <= s1.length (); i++) {a[i][0] =i; } for(intj = 0; J <= S2.length (); J + +) {a[0][J] =J; } for(inti = 1; I <= s1.length (); i++){ for(intj = 1; J <= S2.length (); J + +){ if(S1.getbytes () [i-1] = = S2.getbytes () [j-1]) {A[i][j]= A[i-1][j-1]; } Else{ inttemp = Math.min (A[i-1][j], a[i][j-1]); A[I][J]= Math.min (temp, a[i-1][j-1]) + 1; } } } returna[s1.length ()][s2.length ()]; }}
Public classMain2 { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub /** KMP Algorithm*/String str1= "ABABCABABABDC"; String str2= "ABC"; System.out.println ("FFF"); intindex =KMP (STR1,STR2); SYSTEM.OUT.PRINTLN (index); } Static intKMP (String str1, String str2) {inti = 0; intj = 0; int[] Next =New int[Str2.length ()]; Next=Getnextval (STR2); while(I < Str1.length () && J <str2.length ()) { if(j = =-1 | | str1.getbytes () [i] = =str2.getbytes () [j]) {i++; J++; } Else{J=Next[j]; } } if(J = =str2.length ()) { returnIstr2.length (); } return-1; } Static int[] Getnextval (String str2) {intk=-1; intj = 0; int[] Next =New int[Str2.length ()]; NEXT[J]=-1; while(J < Str2.length ()-1){ if(k = =-1 | | str2.getbytes () [k] = =str2.getbytes () [j]) {next[++J] = + +K; } Else{k=Next[k]; } } returnNext; }}
Classic Algorithm Review 2