Problem: There are two strings str1 and str2, which find the longest common string in two strings.
For example: the longest common string for "Acbbsdef" and "abbsced" is "BBS"
Algorithm ideas:
1, the two strings are composed of rows and columns of a two-dimensional matrix.
2, compare the two-dimensional matrix in the row and column corresponding to the character of each point is the same, is set this point is 1, no set this point is 0.
3. Find the longest common string by looking for the longest diagonal line with a value of 1.
Through the above str1 and str2 two strings, respectively , a two-dimensional matrix consisting of rows and columns, such as :
As you can see, there are 3 common string "BBS"in Str1 and str2, and the common substring length is 3.
To avoid subsequent lookups of diagonal lengths:
The length of the longest common substring can be computed by the way of calculating the value of the two-dimensional matrix first.
That is: The value of a two-dimensional matrix element evolves from Item[i][j]=1 to Item[i][j]=1 +item[i-1][j-1].
Here is the code implementation
Public classMaxstringdemo { Public Static voidMain (string[] args) {String AA= "ABC123EDF"; String BB= "BC123JG"; MAXUTIL2 (AA, BB); System.out.println (MAXUTIL2 (AA, BB)); } Public StaticStringBuilder maxUtil2 (String str1, String str2) {//turn a string into a character array Char[] arr1 =Str1.tochararray (); Char[] arr2 =Str2.tochararray (); //a two-dimensional matrix consisting of two strings in rows and columns, respectively int[] temp =New int[Arr1.length][arr2.length]; //store the longest common substring length intLength = 0; //start indicates the starting point of the longest common substring, and end indicates the end point of the longest common string intEnd = 0; intStart = 0; ////initializes the first row in a two-dimensional matrix for(inti = 0; i < arr2.length; i++) {temp[0][i] = (arr1[0] = = Arr2[i])? 1:0; } //Initialize the first column in a two-dimensional matrix for(intj = 0; J < Arr1.length; J + +) {temp[j][0] = (arr2[0] = = Arr1[j])? 1:0; } //nested for loop: Compares each point in a two-dimensional matrix to the determinant of no equality, the equivalent value is set to 1, otherwise set to 0 for(inti = 1; i < arr1.length; i++) { for(intj = 1; J < Arr2.length; J + +) { if(Arr1[i] = =Arr2[j]) {Temp[i][j]= Temp[i-1][j-1] + 1; if(Temp[i][j] >length) {Length=Temp[i][j]; End=J; } } ElseTemp[i][j]= 0; } } //find the starting point of the longest common substringStart=end-length+1; StringBuilder SB=NewStringBuilder (); //the longest common substring can be found by finding the longest diagonal line with a value of 1 for(intj = start; J < End+1; J + +) {sb.append (arr2[j]); } returnSB; }}
Here, the problem of finding the longest common string of two strings has been resolved!
Java algorithm--Find the longest common string of two strings