让我们这样看待这个问题... 这个解决方案将更加优化,编码也很容易,但是您必须阅读def并且
必须阅读代码才能理解...否则它听起来只是疯狂和复杂的。
思考一下
在您的问题中,您提供了两个示例字符串,让我们将它们视为两个集合,即 {x,y,z},由字符组成...
而且...而且...您的结果子字符串(集)将是两个字符串(集)中共同的
字符,并且将是
连续条目,符合条件的子字符串(ser)将具有
最高数量的条目。
以上是结果的一些属性,但仅在使用以下算法/方法时有效。
我们有两个集合
a = { BAHYJIKLO }
b = { YTSHYJLOP }
取
a
U b = { - , - , H , Y , J , - , - , L , O }
b
U a = {Y , - , - , H , Y , J , L , O , -}
我只是用"
-"或任何特殊/忽略的字符
替换了未
符合联合集的字符。
这样做后,我们有两个字符串,可以轻松提取
HYJ
,
LO
,
Y
,
HYJLO
现在字符串/子字符串比较和不同的处理需要时间,因此我将这些字符串/子字符串写入以空格或不同行分隔的文本文件中... 这样当我读取文件时,我可以获得整个字符串,而不是嵌套循环来定位子字符串或管理临时变量。
在您拥有
HYJ
,
LO
,
Y
,
HYJLO
之后,我认为找到所需的结果不是问题...
注意:如果您开始使用临时变量和嵌套循环在此处理字符串和子字符串,则其解决方案将非常昂贵... 您必须像这样使用文件。
char a[20], b[20];
cin>>a; cin>>b;
int t=0;
open a temporary text file "file1" to write '(built-in-function works here)'
for(int x=0; x<length(a); x++)
{
t=0;
for(int y=0; y<length(b); x++)
{ if( a[x] == b[y]) t=1; }
if(t == 1)
{
write 'a[x]' to the file1 '(built-in-function works here)'
t=0;
}
else
write a 'space' to the file1 '(built-in-function works here)'
}
for(int x=0; x<length(a); x++)
{
t=0;
for(int y=0; y<length(b); x++)
{ if( b[x] == a[y]) t=1; }
if(t == 1)
{
write 'a[x]' to the file1 '(built-in-function works here)'
t=0;
}
else
write a 'space' to the file1 '(built-in-function works here)'
}
char *words[]={"HYJ","LO","Y","HYJLO"};
int size=0,index=0;
for( int x=0; x<length(words); x++)
for( int y=0; x<length(words); y++)
{
if( x!=y && words[x] is a substring of words[y] )
{
if( length(words[x] ) < size )
{
size = length(words[x];
index = x;
}
}
}
cout<< words[x];
}
我写了相关的代码... 如果你需要,给我发邮件,我会把它发送给你... 顺便说一句,我喜欢这个问题,这个算法的复杂度是3n平方。