【YbtOJ高效进阶 字符串-4】字符串环

链接

YbtOJ高效进阶 字符串-4

题目描述

有两个由字符构成的环。

请写一个程序,计算这两个字符环上最长连续公共字符串的长度。

例如,字符串 ABCEFAGADEGKABUVKLM 的首尾连在一起,构成一个环;字符串 MADJKLUVKL 的首尾连在一起,构成另一个环;UVKLMA 是这两个环的一个连续公共字符串。

样例输入

一行,包含两个字符串,分别对应一个字符环。这两个字符串之间用单个空格分开。字符串长度不超过255 ,且不包含空格等空白符。

样例输出

输出一个整数,表示这两个字符环上最长公共字符串的长度。

思路

直接两倍模拟头尾相连,然后枚举是否有相同字符串即可

代码

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

using namespace std;

string s11, s22;
string s1, s2;
int f, ans;

int main()
{
    
    
	cin>>s11>>s22;
	s1 = s11 + s11;
	s2 = s22 + s22;
	int l1 = s1.length();
	int l2 = s2.length();
	if(l1 > l2)
	{
    
    
		swap(s1, s2);
		l1 = s1.length();
		l2 = s2.length();
	}
	for(int i = 0; i < l1 / 2; ++i)
	for(int j = 1; j <= l1 / 2; ++j)
	{
    
    
		f = s2.find(s1.substr(i, j));
		if(f != -1)
		{
    
    
			if(j > ans)
			ans = j;
		}
	}
	cout<<ans;
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/LTH060226/article/details/114412249