/** gets the maximum identical substring of two strings. String S1 = "Maybe Lake Tech is the biggest winner today"; String S2 = "Maybe the lake technology may not be the biggest winner today";
/**gets the maximum identical substring of two strings. String S1 = "Maybe Lake Tech is the biggest winner today"; String s2 = "may become lake technology is not necessarily the biggest winner today"; Train of thought: 1, determine the length of the two string, in the long string to judge whether a short string exists. 2 exists, has been found, stating that the short string is the largest of the same. Does not exist, the short string is shortened in length, and the substring in the short string is obtained and judged in the long string. 3, once there, the search ends. */ Public classthesamestring { Public Static voidMain (string[] args) {String S1= "Maybe Lake Tech is the biggest winner today."; String S2= "may become Lake technology is not the biggest winner today"; /*Define a method: String maxsubstring (S1,S2)*/String maxstring=maxsubstring (S1,S2); System.out.println ("Maximum same substring:" +maxstring); } Public Staticstring maxsubstring (string s1, string s2) {/*judge the length of S1 and S2, which is the long string, which is short string, how clear?*/String Maxstr; String Minstr; /*Judging if the length of the S1 is greater than the length of S2, then MAXSTR is S1, and vice versa is s2 * very suitable for three mesh operation. Because the trinocular operator happens to be the result of an operation.*/Maxstr= (S1.length () >s2.length ())?s1:s2; /*Long determined, it is not difficult to determine the short judgment if maxstr take S1 as long string, then necessarily equals (S1), otherwise is taken S2 as Maxstr*/Minstr= (Maxstr.equals (S1))?s2:s1; /*long string Short string got, need to judge, maxstr there is no MINSTR * idea: * *. Take short strings in long strings, if the maximum length of a short string is in a long string, then the maximal same substring is a short string * Mathematically may be the concept of greatest common divisor. If the short string does not meet, then reduce the length of the short string, then the ratio, the cycle ratio, until the same character appears, intercept this character, return **/ for(inti = 0; I < minstr.length (); i++) { //This step of thinking in the decreasing length of the printing has been analyzed, omitted. for(intStart = 0, end = Minstr.length ()-i; End<= minstr.length (); start++,end++) {String temp=minstr.substring (start, end); if(Maxstr.contains (temp)) {returntemp; } } } return"No identical substring"; }}
View Code
Gets the maximum identical substring of two strings