L2-008. Longest symmetric substring (not looking at a knowledge point)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.