【strstr】#23 A. You're Given a String...

A. You're Given a String...
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).

Input

The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-case Latin letters, and its length doesn't exceed 100.

Output

Output one number — length of the longest substring that can be met in the string at least twice.

Sample test(s)
input
abcd
output
0
input
ababa
output
3
input
zzz
output
2


题意:

给出一个不超过100字符的字符串,请找出至少出现过两次的子串中最长的子串长度


本来吓了一跳……这是DP么……就算是我也不会呀……只能O(n^3)啊……

一看数据……100……

额……直接暴力了…… 这次用的是 strstr(Momstring,Kidstring,Kidlength)函数(返回第一次找到的指针),挺好用的~~

#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>

/*************************************************
strstr
原型:const char * strstr ( const char * str1, cosnt char *str2);
            char * strstr ( char * str1, const char * str2);
参数:	str1,待查找的字符串指针;
		str2,要查找的字符串指针。
说明:	在str1中查找匹配str2的子串,并返回指向首次匹配时的第一个元素指针。
		如果没有找到,返回NULL指针。
***************************************************/


using namespace std;
int main()
{
	//freopen("in.txt","r",stdin);
	char line[101];
	char find[100];
	scanf("%s",line);
	int len=strlen(line);
	for(int l=len-1;l>0;l--)
	{
		for(int i=0;i<=len-l;i++)
		{
			strncpy(find,line+i,l);//从line里的第i位开始,数l个字符的字符串扔给find
			find[l]='\0';//很重要,不封口简直是作死
			if(strstr(strstr(line,find)+1,find))//找到一个,然后在他后头一位开始找第二个
			{
				printf("%d",l);
				return 0;
			} 
		}
	}
	printf("0");
	return 0;
}

【Updated 2016/01/18】

 其实可以O(n^2)直接记录下有多少子串,用map来hash记数,当出现次数不小于2时更新maxlen即可。

#include <map>
#include <cstdio>  
#include <string>  
#include <cstring>  
#include <iostream>  
#include <algorithm>  
using namespace std;  
map <string,int> mii;
map <string,int>::iterator it;
int main()
{
	int ans = 0 ;
	string s; cin>>s;
	for(int i=0;i<s.length();i++)
		for(int j=i+1;j<=s.length();j++)
		{
			string cur = s.substr(i,j-i);
			//cout<<cur<<endl;
			mii[cur]++;	
			if (mii[cur]>=2) ans = cur.length()>ans ? cur.length():ans;
		}
	cout<<ans<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖果天王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值