Question:
Ideas
Method 1: determine each substring of a string. If it is symmetric, obtain its length. This method is used to determine whether a substring is a substring from both ends to the middle. The total time complexity is O (n ^ 3 ),
The time complexity is O (n ^ 2.
Method 2: opposite to the method, each start in the string is extended to both sides, which can be divided into two situations:
(1) When the length of a symmetric substring is an odd number, the current character is used as the symmetric extension on both sides of the axial direction.
(2) When the length of a symmetric substring is an even number, the current character and the character on the right of the substring are symmetric and axial extension on both sides.
1 # include <cstdio> 2 # include <cstring> 3 int maxsubstring (char * Str) 4 {5 Int length = 1, newlength, I; 6 int left, right; 7 int Len = strlen (STR); 8 for (I = 0; I <Len; I ++) 9 {10 newlength = 1; // symmetry may be odd when 11 left = I-1; 12 Right = I + 1; 13 for (; left> = 0 & right <Len; left --, right ++) 14 if (STR [left] = STR [right]) 15 newlength + = 2; 16 else17 break; 18 if (newlength> length) 19 length = newlength; 20 21 newlength = 0; // If symmetry is an even number, 22 left = I; 23 Right = I + 1; 24 for (; left> = 0 & right <= Len; left --, right ++) 25 if (STR [left] = STR [right]) 26 newlength + = 2; 27 else28 break; 29 If (newlength> length) 30 length = newlength; 31} 32 return length; 33} 34 int main () 35 {36 char STR [1005]; 37 gets (STR); 38 int ret; 39 ret = maxsubstring (STR); 40 printf ("% d \ n", RET); 41 return 0; 42}
View code
There is an O (N)
I checked http://www.cnblogs.com/biyeymyhjob/archive/2012/10/04/2711527.html online
Take a look .. After all, the speed is much faster than traversal...
L2-008. Longest symmetric substring (not looking at a knowledge point)