1 PackageString.demo;2 /*Requirement: Find the longest common substring of two strings3 * Ideas:4 * 1. See if the short string is in the long string, and if it exists, the short string is the largest common substring.5 * 2. If it does not exist, then the short substring is reduced in length to take the substring, to determine whether there is a long string, if6 * exist, find! 7 * 8 */9 Public classfindmostlargesubstringTen { One A /** - * @paramargs - */ the Public Static voidMain (string[] args) - { -String S1 = "Qwerabcdtyuiop"; -String s2 = "Xcabcdvbn"; +String s =getmaxsubstring (S1, S2); -System.out.println ("s =" +s); + } A at /** - * Get maximum substring - * @paramS1 - * @paramS2 - * @return - */ in Private Staticstring getmaxsubstring (string s1, string s2) - { toString max =NULL; +String min =NULL; -Max = (s1.length () > S2.length ())?s1:s2; themin = max.equals (S1)?s2:s1; * for(inti = 0; I < min.length (); i++) $ {Panax Notoginseng for(intA = 0, B = min.length ()-I; b! = min.length () + 1; a++, b++) - { the //takes a substring of a short string and determines whether the substring exists in a long string +String Sub =min.substring (A, b); A if(Max.contains (sub)) the returnSub; + } - } $ return NULL; $ } - -}
Maximum same substring of Java practice