1. Description
Enter a string that prints the maximum length of the symmetric substring in the string. For example, the input string "Goooogle", because the longest symmetric substring in the string is "Goooog", so output 6.
2. Ideas
Method one: To determine the string of each substring, if symmetric, then find its length. This method determines whether a substring is in the middle of each substring, from both ends. The total time complexity is O (n^3),
The following is an O (n^2) idea of time complexity.
Method Two: In contrast to method one, each beginning of a string, extending to both sides, can be divided into two situations:
(1) When the length of the symmetric substring is odd, the comparison is extended to both sides with the current character as the axis of symmetry
(2) When the length of the symmetric substring is an even number, the current character and its right character are extended to both sides of the axis.
3. Code
To make it clearer, a small algorithm that determines whether a string is symmetric is given first:
int issymstring (char str[])
{
if (! Str)
return;
Char *start, *end;
start = str;
end = str + strlen (str)-1;
for (; start < end; ++start,--end)
if (*start! = *end)//unsymmetrical
return 0;
return 1; Symmetrical
}
Here is the formal algorithm for finding the length of a symmetric substring in a string:
int maxsymsubstring (char str[])
{
char *fromstart2end, *left, *right;
int length = 1, newlength;
for (fromstart2end = str; *fromstart2end; fromstart2end++)
{
newlength = 1; The symmetric substring may be odd when left
= fromstart2end-1;
right = Fromstart2end + 1;
for (; left >= str && right <= str + strlen (str)-1;--left, ++right)
if (*left = = *right) Newlen Gth + = 2;
else break ;
if (newlength > Length)
length = newlength;
newlength = 0; The symmetric substring may be even when left
= fromstart2end;
right = Fromstart2end + 1;
for (; left >= str && right <= str + strlen (str)-1;--left, ++right)
if (*left = = *right) Newlen Gth + = 2;
else break ;
if (newlength > Length)
length = newlength;
} for
return length;
}
The test is as follows:
#include <stdio.h>
#include <string.h>
int maxsymsubstring (char str[]);
int main (void)
{
char str[] = "Goooogle";
int ret;
ret = maxsymsubstring (str);
printf ("%d\n", ret);
return 0;
}
Output: