Recently encountered in the project such a problem, to compare JS and CSS has been modified, first think of the use of third-party tools found not found, and then thought, this problem is not the first line of two files to find the largest common substring, since it is required to the maximum length of the common substring, thus thought of the dynamic programming algorithm.
The code is rewritten from the online C + +, thanks to the brother of C + +, the code is as follows:
PackageDP;/*** Solving the longest common substring with dynamic programming algorithm *@author * */ Public classLcssuffix {Private Staticstring Getlcslength (String s,string t) {intp =s.length (); intQ =t.length (); string[][] Num=NewString[p][q]; CharChar1 = ' + '; CharChar2 = ' + ' ; intLen = 0 ; String LCS= ""; for(inti = 0;i<p; i++){ for(intj=0;j<q;j++) {char1=S.charat (i); Char2=T.charat (j); if(Char1! =char2) {Num[i][j]= ""; }Else { if(i==0) Num[i][j] =string.valueof (CHAR1); Else if(j ==0) Num[i][j] =string.valueof (CHAR2); ElseNUM[I][J] = num[i-1][j-1] +string.valueof (CHAR1); if(Num[i][j].length () >Len) {Len=num[i][j].length (); LCS=Num[i][j]; }Else if(num[i][j].length () = =Len) {LCS= LCS + "," +Num[i][j]; } } } } returnLCS; } Public Static voidMain (string[] args) {String LCS= Getlcslength ("Baba", "Abab"); SYSTEM.OUT.PRINTLN (LCS); }}
Java Dynamic programming algorithm solves the longest common substring