漫长的假期结束了,是时候重新开干了。但是好像没想象中的那么顺利。
今天看了一下新的题组,很好,好像没怎么看懂。虽然是字符串匹配,但是好像没想象中的那么容易。翻了翻《大话数据结构》的kmp部分,发现好像看不太懂,尝试着跟着书上的范例写了一个kmp模板,发现运行错误,可能是还没有理解透彻吧。然后又翻了翻网上对于hash和kmp的见解和基本模式,还是无法理解,不过今天还是做出了一道题目。
题目描述
The cows enjoy mooing at the barn because their moos echo back, although sometimes not completely. Bessie, ever the excellent
secretary, has been recording the exact wording of the moo as it goes out and returns. She is curious as to just how much overlap there is.
Given two lines of input (letters from the set a..z, total length in the range 1..80), each of which has the wording of a moo on it, determine the greatest number of characters of overlap between one string and the other. A string is an overlap between two other strings if it is a prefix of one string and a suffix of the other string.
By way of example, consider two moos:
moyooyoxyzooo
yzoooqyasdfljkamo
The last part of the first string overlaps 'yzooo' with the first part of the second string. The last part of the second string
overlaps 'mo' with the first part of the first string. The largest overlap is 'yzooo' whose length is 5.
POINTS: 50
奶牛们非常享受在牛栏中哞叫,因为她们可以听到她们哞声的回音。虽然有时候并不能完全听到完整的回音。Bessie曾经是一个出色的秘书,所以她精确地纪录了所有的哞叫声及其回声。她很好奇到底两个声音的重复部份有多长。
输入两个字符串(长度为1到80个字母),表示两个哞叫声。你要确定最长的重复部份的长度。两个字符串的重复部份指的是同时是一个字符串的前缀和另一个字符串的后缀的字符串。
我们通过一个例子来理解题目。考虑下面的两个哞声:
moyooyoxyzooo
yzoooqyasdfljkamo
第一个串的最后的部份"yzooo"跟第二个串的第一部份重复。第二个串的最后的部份"mo"跟第一个串的第一部份重复。所以"yzooo"跟"mo"都是这2个串的重复部份。其中,"yzooo"比较长,所以最长的重复部份的长度就是5。
输入格式
* Lines 1..2: Each line has the text of a moo or its echo
输出格式
* Line 1: A single line with a single integer that is the length of the longest overlap between the front of one string and end of the other.
输入输出样例
输入 #1复制
abcxxxxabcxabcd abcdxabcxxxxabcx
输出 #1复制
11
说明/提示
'abcxxxxabcx' is a prefix of the first string and a suffix of the second string.
这道题目因为只有前缀和后缀,而且长度很短很短,所以这道题我觉得暴力也能过。C++只要善用string类的方法substr就可以很快速地把这道题给过了。分别剪切两段文本的前缀和后缀,然后交叉比较,相同就记录长度,节省算力的话可以从最长的串开始比,先假设前缀和后缀都是最短的字符串长度,然后再一位位减下来就可以完成长度记录了。
#include <bits/stdc++.h>
using namespace std;
string S, T;
int main()
{
cin >> S >> T;
int size = min(S.size(), T.size());
int len1 = 0, len2 = 0;
for(int i = size;i >= 1;i --) //前缀和后缀对比是否相同,按最长的算
{
if(S.substr(0, i) == T.substr(T.size() - i, i))
{
len1 = i;
break;
}
}
for(int i = size;i >= 1;i --) //对调位置对比
{
if(T.substr(0, i) == S.substr(S.size() - i, i))
{
len2 = i;
break;
}
}
cout << max(len1, len2); //输出最长的相似字符串长度
return 0;
}
所以明天还是再看看hash和kmp吧,今天没问群友,因为感觉自己可以搞定的(很明显地打脸了),明天如果实在解决不了就去问问友好的群友吧()。剩下的题目要么用hash要么用kmp了,至少还是得把模板学过来先。