5. Longest palindromic Substring

Source: Internet
Author: User

Given a string S, find the longest palindromic substring in s. The maximum length of S is assume, and there exists one unique longest palindromic substring.

Given the string s, find its longest palindrome substring. Suppose that the longest length of S is 1000 and only one eldest string.

This problem has a variety of solutions, you can use dynamic programming, the formula is: P (i, j) = P (i+1, J-1) && (s[i] = = S[j]), according to the length limit, the auxiliary space can be statically set to 1000*1000, time complexity is O (n*n),

Space is also O (n*n), can also be traversed from one side to the other, until the discovery of asymmetric characters, it is important to note that Palindrome Sub-center characters and no central character two cases, respectively consider the line, time complexity is O (n*n),

But the space only needs O (1), so this article uses the second, the code is as follows:

stringLongestpalindrome (strings) {intn =s.size (); stringret;  for(intI=0; i<n; ++i) {intL = i, R =i;  while(l>=0&& r<n && s[l] = =S[r]) {            --l; ++R; }        ++l; --R; if(Ret.size () < r-l+1) ret= S.substr (L, r-l+1); L= i; R = i+1;  while(l>=0&& r<n && s[l] = =S[r]) {            --l; ++R; }        ++l; --R; if(Ret.size () < r-l+1) ret= S.substr (L, r-l+1); }    returnret;}

5. Longest palindromic Substring

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.