Longest palindromic substring-leetcode

Source: Internet
Author: User

Question

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exist one unique longest palindromic substring.

 

Analysis and Solution

If a string is a return, the prefix and suffix centered on a character are the same. for example, if a text string "ABA" is centered on B, its prefix and suffix are the same.

Therefore, we can enumerate the central position, expand it to the left and right sides, record and update the retrieval length. The Code is as follows:

 

Strng longestpalidrome (string s) {int I, j, Max, C; max = 0; string ret; for (I = 0; I <S. size (); I ++) {for (j = 0; (I-j> = 0) & (I + j <n); j ++) {// assume that it is only an odd string, if (s [I-j]! = S [I + J]) break; C = J * 2 + 1;} If (C> MAX) {ret = S. substr (I-j + 1, C); max = C ;}for (j = 0; (I-j> = 0) & (I + J + 1 <n); j ++) {// assume this is an even string if (s [I-j]! = S [I + J + 1]) break; C = J * 2 + 2;} If (C> MAX) {ret = S. substr (I-j + 1, C); max = C;} return ret ;}

 

The time complexity is O (n ^ 2 ).

There is also an O (n) Time Complexity Algorithm on the Internet, more complex. can refer to: http://blog.csdn.net/feliciafay/article/details/16984031

 

Longest palindromic substring-leetcode

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.