標籤:java 記憶體 數組越界 kmp
點擊開啟杭電2549
Problem DescriptionHomer: Marge, I just figured out a way to discover some of the talents we weren’t aware we had.
Marge: Yeah, what is it?
Homer: Take me for example. I want to find out if I have 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 Clinton’s name that is a suffix in my name. That’s how close I am to being a politician like Clinton
Marge: Why on earth choose the longest prefix that is a suffix???
Homer: Well, our talents are deeply hidden within ourselves, Marge.
Marge: So how close are you?
Homer: 0!
Marge: I’m not surprised.
Homer: But you know, you must have some real math talent hidden deep in you.
Marge: How come?
Homer: Riemann and Marjorie gives 3!!!
Marge: Who the heck is Riemann?
Homer: Never mind.
Write a program that, when given strings s1 and s2, finds the longest prefix of s1 that is a suffix of s2.
InputInput consists of two lines. The first line contains s1 and the second line contains s2. You may assume all letters are in lowercase.
OutputOutput consists of a single line that contains the longest string that is a prefix of s1 and a suffix of s2, followed by the length of that prefix. If the longest such string is the empty string, then the output should be 0.
The lengths of s1 and s2 will be at most 50000.
Sample Input
clintonhomerriemannmarjorie
Sample Output
0rie 3
注意:主要要注意java裡記憶體的控制,和數組的越界情況。(這裡坑死我了!!)
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)+" ");//這裡要是不用substring,而用for迴圈,就會超記憶體。 } 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這裡不用要j<len2但是java必須要,因為java比較嚴格,不允許越界情況,而c允許(java通常屬於解析型語言,它是一句一句解釋,而c是通篇解釋)。<span style="font-family: Arial, Helvetica, sans-serif;">同理</span><span style="font-family: Arial, Helvetica, sans-serif;">j==-1一定要放在前面。</span>
i++; j++;//System.out.print("** "); }else{ j=next[j]; }//System.out.print(j+"* "); }//System.out.println(); return j; }}
杭電2549(第一次用java寫kmp演算法)