Click to open Hangzhou electric 2549
problem DescriptionHomer:marge, I just figured out a-to discover some of the talents we weren ' t aware we had.
Marge:yeah, what's it?
Homer:take me for example. I want to find out if I had a talent in politics, OK?
Marge:ok.
Homer:so I Take some politician's name, say Clinton, and try to find the length of the longest prefix
In the Clinton ' s name is a suffix in my name. That's how close I'm to being a politician like Clinton
Marge:why on Earth Choose the longest prefix a suffix???
Homer:well, our talents is deeply hidden within ourselves, Marge.
Marge:so How close is you?
homer:0!
Marge:i ' m not surprised.
Homer:but know, you must has some real math talent hidden deep in.
Marge:how come?
Homer:riemann and Marjorie gives 3!!!
Marge:who the heck is Riemann?
Homer:never mind.
Write a program this, when given strings S1 and S2, finds the longest prefix of S1, which is a suffix of s2.
InputInput consists of lines. The first line contains S1 and the second line contains S2. Assume all letters is in lowercase.
OutputOutput consists of a single line this contains the longest string that was a prefix of S1 and a suffix of S2, followed by t He length of that prefix. If the longest such string is the empty string and then the output should be 0.
The lengths of S1 and S2 would be in most 50000.
Sample Input
Clintonhomerriemannmarjorie
Sample Output
0rie 3
Note: It is important to note the control of memory in Java, and the array of cross-border situations. (It's killing me!!) )
Import Java.util.*;class main{static int[] Next=new int[50005]; Static String str1,str2; static int len1,len2; public static void Main (String args[]) {int n,i; Scanner sc=new Scanner (system.in); while (Sc.hasnext ()) {str2=sc.nextline (); Str1=sc.nextline (); Len1=str1.length (); Len2=str2.length (); N=KMP (); if (n>0) {System.out.print (str2.substring (0,n) + ");//If the substring is not used here, it will be hyper-memory with a for loop. } System.out.println (n); }} public static void Set_next () {int i=0,j=-1; Next[0]=-1; while (I<LEN2) {if (j==-1| | Str2.charat (i) ==str2.charat (j)) {i++; j + +; Next[i]=j;///system.out.print (next[i]+ ""); }else{J=next[j]; }}//system.out.println (); } public static int kmp () {int i=0,j=0; Set_next (); WhilE (i<len1) {//system.out.print (j+ ""); if (j==-1| | (J<len2&&str1.charat (i) ==str2.charat (j))) {//c There's no need to j<len2 here, but Java has to be, because Java is stricter and does not allow out-of-bounds, and C allows (Java is usually a parsing language, it is an explanation, and C is an entire explanation). <span style= "font-family:arial, Helvetica, Sans-serif;" > similarly </span><span style= "font-family:arial, Helvetica, Sans-serif;" >j==-1 must be put in front. </span>
i++; J++;//system.out.print ("* *"); } else{ j=next[j]; } System.out.print (j+ "*"); } System.out.println (); return j; }}
Hangzhou Electric 2549 (first time with Java write KMP algorithm)