又是最大公共字符串问题(注意什么能减少判断)

已经第三次发现问题了,还是得记录下来,毕竟我是菜鸟

题目:给定两个字符串,求他的最长公共字符串,并输出,若没有返回NULL


这是我写的:没有算法可言,只是出了结果:

#include <iostream>
#include<string>
using namespace std;
typedef char* String;
 String temp;
String iQueryMaxCommString(String s, String t)
{
 int len1,len2,i,j,k,len=0,maxlen=0,pos=0;

 len1=strlen(s);
 len2=strlen(t);
 i=0;

 while(i<len1)
 {
  j=0;
  while(j<len2)
  {
   if(s[i]==t[j])
   { j=1;
    len=1;
    for(k=1;k+i<len1&&k+j<len2&&s[k+i]==t[k+j];k++)
     len++;
    if(len>maxlen)
    {
     maxlen=len;
     pos=i;
    }
   }
   j++;
  }
  i++;

 }

 temp=new char[maxlen+1];

 if(maxlen!=0)
 {
  for(i=0;i<maxlen;i++)
  { temp[i]=s[pos+i];
   cout<<s[pos+i];
  }

   temp[pos+i]='\0';
  // cout<<temp<<endl;

return temp;
 }
 else 
  return NULL;

 }
void  main()
{
// String a,b;
 String a=new char[100];
 String b=new char[100];
 gets(a);
 gets(b); 
iQueryMaxCommString(a, b);
//return 0;


}



这是网上找的,来自静水流深的代码(我把他的略作修改了,仅仅是为了保证借口满足题意的借口,但是奇怪的是它的结构比题目多了一个参数,提交还是算对了):

#include <iostream>
using namespace std;
int MaxSubstring(char str[],char a[])
{
 //,char *&s
 int num=0;   //公共串的长度;
 int max=0;
 int i;
 int start,start1,start2;
 for(i=0; str[i]!='\0'; i++)
  for(int j=0; a[j]!='\0'; j++)              //这里用for肯定比我while一下再去自加好
  {
   start1=i;
   start2=j;
   while(str[start1] && a[start2] && str[start1++]==a[start2++])         //这里比我的少做了==的判断
    num++;
   if(num>max)
   {
    start=i;
    max=num;
   }
   num=0;
  }
 // s=new char[max+1];
  for(i=0;i<max;i++)
  // s[i]=str[i+start];
    cout<<str[i+start];
  str[i+start]='\0';
 // s[max]='\0';
  return max;
}

int main()
{
 char a[100],b[100];
// char *array;
 int i;
 gets(a);
 gets(b);
 //,array
 int length=MaxSubstring(a,b);
// for(i=0;i<length;i++)
//  cout<<array[i];
//  
 cout<<endl;
}


最终的结果是什么?

我觉得我的和静水流深的想法是一样的,只是有一点点不太一样,主要在for 和while那里,

结果静水流深的提交得了200分,我的提交显示:运行时间超时(题目要求1min),0分。

这让我感觉到平时还是要注意一下书写习惯啊,即使你觉得无所谓,出结果就行,但是时间也要做考虑的,能省略的判断肯定要省略的!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值