本帖最后由 陈圳 于 2013-2-25 13:16 编辑
老师的解法:- public String getMaxString(String s1,String s2)
- {
- String max="",min="";
- max=(s1.length()>s2.length())?s1:s2;
- min=(max.length()==s1.length())?s2:s1;
- for(int x=0;x<min.length();x++)//循环小串长度
- {
- for(int y=0,z=min.length()-x;z!=min.length();y++,z++)
- {
- String temp=min.substring(y,z);
- if(max.contains(temp))
- return temp;
- }
- }
- return "";
- }
复制代码 如:String s1="dsfhellojahellojavaoo",s2="java hellojavaodfafd hellojavaoosdfasd"
最大子串应为:hellojavaoo;
实现打印结果为:hellojavao;
因为获取到了多个子串,但没有判断,所有取了一个就当结果了.
我看了题目,然后自己解题;//用的是老师说的效率低的办法...但我感觉效率不低...
我做了计数,我的循环次数少一些.我另外定义的变量是为了判断是否有重复变量.如果老师的函数要解决这个问题,也需要定义,这俩个方法,到抵哪个效率高一些?- package Day15;
- class Test1
- {
- String s="haha";
- public static void main(String[] args)
- {
- String s1=new Test1().getString("dsfhellojahellojavaoo","java hellojavaodfafd hellojavaoosdfasd");
- System.out.println(s1);//我自定义的
- String s2=new Test1().getMaxString("java hellojavaodfafd hellojavaoosdfasd", "dsfhellojahellojavaoo");
- System.out.println(s2);//老师的解法
- }
- public String getString(String string1,String string2)
- {
- int count=0;//定义一个循环计数变量
- int begin=0,end=1;
- String max="",min="";
- max=(string1.length()>string2.length())?string1:string2;
- min=(max.length()==string1.length())?string2:string1;
- String s1="",s2="",s3="";
- int i=0;
- while(end<=min.length())//运算的最大步数不能大于min小串的长度,否则越界了.
- {
- System.out.println("循环次数为:"+count+"次");
- count++;
- s1=min.substring(begin,end);
- if(max.contains(s1))
- {
- end++;
- s3=s1;
- if(s2.length()<s3.length()||(s2.length()==s3.length()&&s2.compareTo(s3)<0))
- s2=s3;
- }
- if(!max.contains(s1))//不属于他的子串时
- {
- begin++;//
- }
- }
- return s2;
- }
- public String getMaxString(String s1,String s2)
- {
- int count=0;//定义循环计数变量
- String max="",min="";
- max=(s1.length()>s2.length())?s1:s2;
- min=(max.length()==s1.length())?s2:s1;
- for(int x=0;x<min.length();x++)//循环小串长度
- {
- for(int y=0,z=min.length()-x;z!=min.length();y++,z++)
- {
- count++;
- System.out.println("循环次数为:"+count+"次");
- String temp=min.substring(y,z);
- if(max.contains(temp))
- return temp;
- }
- }
- return "";
- }
-
- }
复制代码 getString:hellojavaoo
getMaxString:hellojavao
|