Idea: Introduce the idea of a matrix, the string A (length m) as a matrix of rows, the string B (length n) when the matrix column, so that constitutes a m*n matrix. If the node of the matrix corresponds to the same character, i.e. M[i]=n[j], the node value is 1, the current character is the value of the same node = the upper-left corner (D[i-1, J-1]), and the value of the current node is the maximum common substring length. You can intercept the maximum substring simply by the line number and the maximum value.
PublicStringgetlongest(String s1,string S2) {if(s1==NULL|| s2==NULL){return NULL; }if(S1.equals (S2)) {returnS1; }intLength =0;intEnd =0;int[] A =New int[S1.length ()] [S2.length ()];Char[] Char1=s1.tochararray ();Char[] Char2=s2.tochararray (); for(inti =0; I < s1.length (); i++) { for(intj =0; J < S2.length (); J + +) {intn = (I-1>=0&& J-1>=0) ? A[i-1][j-1] :0;//Current value is the last node value plus 1 a[i][j]=a[i-1][j-1]+1;A[I][J] = (char1[i] = = Char2[j])?1+n:0;//Determine if the longest string length is greater than before if(A[i][j] > length) {//Hold length as the longest public string lengthlength = A[i][j];//end to the end of the longest public stringend = i; } } }returnS1.substring (End-length +1, end+1); }
The longest common string (JAVA) for string A and string b