广大校赛第八届C题

来源:互联网 发布:黑白网络网址 编辑:程序博客网 时间:2024/06/02 14:41

Camel Zombies

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 128000/64000 KB (Java/Others)
SubmitStatistic Next Problem

Problem Description

The string of Zombies(Camel Zombies) gives you a question :

    Given you a string, STR, with up to 50 characters, find the length of the longest substring(子串) that appears at least twice (non-overlapping)(不重叠) in STR. If no substring appears twice, non-overlapping, output 0.


    Strings are case sensitive(大小写敏感), and only upper case letters and lower case letters are allowed in input.


    For example, in the string "ABCDEXXXYYYZZZABCDEZZZYYYXXX" the longest substring which appears at least twice is "ABCDE".

    These two substrings do not overlap so you would output 5.

Input

The input begins with a positive integer T indicating the number of the cases following, each of them as described below.
-->The first line is a string STR 1 <= STR’s length <= 50).

Output

The output of each case should include an integer NN is the length of the longest substring which appears at least twice(NOT overlap).

Sample Input

3ABCDEXXXYYYZZZABCDEZZZYYYXXXabcdabcdabcdabCDagainANDagainANDagainANDagainANDagainANDagain

Sample Output

5621

Hint

Explain for the two cases in the sample input :
case 1 : The example from above.
case 2 : "abcdab"+"cd"+"abcdab"+"CD"

PS:这道题英文那么多,其实就是求给出的字符串中,最长的相同的不重叠的子字符串的长度


代码如下:

#include<iostream>#include<string>using namespace std;int main(){int t;cin >> t;while (t--){string str;cin >> str;int len = str.length();//输入的字符串长度int blen = len / 2;//我们只要从一半开始检测就好了,因为如果子串长度超过原字符串长度的一半,那如果找到相同的肯定是重叠的bool issearch = false;//是否已经找到for (int i = blen; i > 0 && !issearch; --i){//for (int j = 0; j < len - i; ++j)  做了优化
<span style="white-space:pre"></span><pre name="code" class="cpp"><span style="white-space:pre"></span>for (int j = 0; j < len - 2 * i; ++j)
{string s = str.substr(j, i);//获取子字符串int cur = str.find(s, j + i);//再字符串中改子字符串后面剩下的字符串中查找,找不到则是-1if (cur != -1 && (cur < j || cur >= j + i)){cout << s.length() << endl;i = 0;issearch = true;break;}}}if (!issearch){cout << 0 << endl;}}return 0;}


0 0
原创粉丝点击