杭电2549(第一次用java写kmp算法)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了杭电2549(第一次用java写kmp算法),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2723字,纯文字阅读大概需要4分钟。
内容图文
![杭电2549(第一次用java写kmp算法)](/upload/InfoBanner/zyjiaocheng/1298/1dd48624849d47bb9a31ff63c3b78ac1.jpg)
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.
The lengths of s1 and s2 will be at most 50000.
clinton homer riemann marjorie
0 rie 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; } }
原文:http://blog.csdn.net/u011479875/article/details/44996567
内容总结
以上是互联网集市为您收集整理的杭电2549(第一次用java写kmp算法)全部内容,希望文章能够帮你解决杭电2549(第一次用java写kmp算法)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。