Concatenate the input string twice like:
s1 = ABCDEFABCDEF
s2 = KLMNABKLMNAB
for string (ABCDEF) and (KLMNAB)
Restriction: The longest Ring would not be longer than the minimum length of the 2 original strings, Keep this restriction through out ur algorithm
WARNING!: THIS IS NOT A LCS PROBLEM, adjacent substrings are demanded
最后字符串比较,追求效率的话用KMP。普通匹配也能过。
代码:
# include <iostream>
# include <string>
# include <algorithm>
using namespace std;
class stringCompare{
private:
string s1;
string s2;
public:
stringCompare(string& s1_, string& s2_)
{
s1 = s1_ + s1_;
s2 = s2_ + s2_;
int len1 = s1.length();
int len2 = s2.length();
}
int patterning(string& target, string& pattern)
{
int targetLen = target.length();
int patternLen = pattern.length();
int longestRing = patternLen;
int i = 0;
int j = 0;
int externalLoop = 0;
int internalLoop = 0;
string substring1;
string substring2;
for ( longestRing = patternLen; longestRing >=1; longestRing-- )
{
externalLoop = targetLen - longestRing;
internalLoop = patternLen - longestRing;
for ( i = 0; i <= externalLoop; i++ )
{
for ( j = 0; j <= internalLoop; j++ )
{
substring1 = target.substr(i,longestRing);
substring2 = pattern.substr(j,longestRing);
if ( substring1 == substring2 )
{
return longestRing;
}
}
}
}
return longestRing;
}
int findMax()
{
int max = 0;
if ( s1.length() >= s2.length() )
{
max = patterning(s1,s2);
}
else
{
max = patterning(s2,s1);
}
return max;
}
};
int main()
{
string inputString1;
string inputString2;
int maxRing = 0;
while ( cin >> inputString1 >> inputString2 )
{
maxRing = 0;
if ( inputString1.length() == 1 || inputString2.length() == 1 )
{
break;
}
stringCompare cmp(inputString1,inputString2);
maxRing = cmp.findMax();
cout << maxRing << endl;
}
return 0;
}