ClassicAlgorithmQuestion -- obtain the maximum length of the countermeasure string (version 2)
Method 1: The idea is quite satisfactory. traverse this string. If two adjacent characters are found to be equal, cyclically judge whether the two adjacent characters are equal,
Keep down the number of characters that meet the conditions. The maximum number is required. (This method is suitable for strings such as Google)
Method 2: The train of thought is the same as the method at the moment. It is suitable for strings such as ggoggle.
Method 3: Meet the meaning of the question, suitable for any type of string. The time complexity is O (n ^ 2 ).
Method 1
Int Counterplan1 ( Const String Str)
{
Int Strlen = Str. Length ();
Int Maxlen = 0 ;
For ( Int I = 0 ; I < Strlen - 1 ; I ++ )
{
If (STR [I] = STR [I + 1 ])
{
Int Start = I - 1 ;
Int End = I + 2 ;
While (Start > 0 && End < Strlen)
{
If (STR [start] = STR [end])
{
-- Start; ++ End;
} Else
{
Break ;
}
}
If (Maxlen < End - Start - 1 )
{
Maxlen = End - Start - 1 ;
}
}
}
Return Maxlen;
}
Method 2
Int Counterplan2 ( Const String Str)
{
Int Strlen = Str. Length ();
Int Maxlen = 0 ;
For ( Int I = 1 ; I < Strlen - 1 ; I ++ )
{
If (STR [I - 1 ] = STR [I + 1 ])
{
Int Start = I - 1 ;
Int End = I + 2 ;
While (Start > 0 && End < Strlen)
{
If (STR [start] = STR [end])
{
-- Start; ++ End;
} Else
{
Break ;
}
}
If (Maxlen < End - Start)
{
Maxlen = End - Start;
}
}
}
Return Maxlen;
}
Method 3
Int Counterplan3 ( Const String Str)
{
Int Strlen = Str. Length ();
Int Maxlen = 0 ;
Int Start = 0 , End = Strlen - 1 ;
While (Start < End)
{
If (STR [start] ! = STR [end])
{
If (Start = End)
{
++ Start;
End = Strlen - 1 ;
} Else {
-- End;
Continue ;
}
}
Int I = Start, J = End;
Bool Isok = False ;
While (I < J && ! Isok ){
While (STR [ ++ I] = STR [ -- J])
{
If (I < J - 2 )
{
Continue ;
}
If (End - Start + 1 > Maxlen)
{
Maxlen = End - Start + 1 ;
}
Isok = True ;
Break ;
}
I = ++ Start; j = End;
}
If (Strlen - Start <= Maxlen - 1 )
{
Break ;
}
}
Return Maxlen;
}