Function: Determine whether a number contains two identical substrings (at least the string length is greater than or equal to 2) and outputs (output only the same substring for the first time)
1 PackageRen.laughing.test.problem;2 3 ImportJava.util.Scanner;4 5 /**6 * Function: Determine if a number contains two identical substrings (at least the string length is greater than or equal to 2) and output (output only the same substring for the first time)7 * 8 * @authorLaughing_lz9 * @time July 4, 2016Ten */ One Public classChildstr { A PrivateString str; - - /** the * Determine if the input string is legal - */ - Public voidinput () { -Scanner sc =NewScanner (system.in); +str =sc.nextline (); - sc.close (); + if(Str.isempty ()) {//if the input is empty Astr =NULL; at return; - } - for(inti = 0; I < str.length (); i++) { - Charc =Str.charat (i); - if(Str.isempty () | | | (c >= ' a ' && c <= ' z ') | | (c >= ' A ' && C <= ' Z ') | | (c >= ' 0 ' && C <= ' 9 '))) {//Restriction conditions -str =NULL; in return; - } to } + } - the /** * * Search Algorithm $ */Panax Notoginseng Public voidsearch () { - if(str = =NULL) { theSystem.out.println ("Input string Error! "); + return; A } the intj = 1;//The index is defined here out of two loops and can be implemented in a single loop with J always and I synchronized progression ★ + intNumber = 0;//record the same substring length - intindex = 0;//record string start position $ for(inti = 0; I < Str.length ()-1; i++) { $ CharNumi = Str.charat (i);//Current Position number - if(i = = Str.length ()-2 | | j = =str.length ()) { -Number = 0;//return number to 0 thej = i + 1;//after a loop, move J back to the i+1 start point and traverse - }Wuyi for(; J < Str.length (); j + +) { the CharNUMJ =Str.charat (j); - if(Numi = =NUMJ) { Wunumber++; - if(J < Str.length ()-1) { Aboutj + +;//before judging the next number, J + + $ } - Break; -}Else { - if(Number >= 2) { A Break; +}Else { theNumber = 0;//if only 1 digits are encountered, place number 0 when different numbers are encountered - } $ } the } the if(Number >= 2 && str.charat (i + 1)! = Str.charat (j)) {//when the same number is greater than 2, a different number is encountered immediately exiting the loop, printing the substring theindex = i + 1; the Break; - } in } the if(Number >= 2) { theSystem.out.println ("exists, string is:" + str.substring (Index-Number , index)); About } the } the the Public Static voidMain (String arg[]) { +CHILDSTR cs =Newchildstr (); - cs.input (); the Cs.search ();Bayi } the}
Determines whether a number contains two identical substrings and outputs