Leetcode: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.

Analysis:

This problem is similar to longest Valid parentheses, except that Valid parentheses each extension is two characters, and Palindrome can expand one character at a time. In the dynamic programming algorithm, valid parentheses can make a memo with a one-dimensional array, and palindrome needs a two-dimensional array. The subject is sometimes complex O (n), spatial complexity O (n) algorithm, see Leetcode.pdf Page65 's Manacher ' s algorithm. The dynamic programming method used here is O (n^2) for both time complexity and space complexity, but the data structure with vector is timed out. The code is as follows:

classSolution { Public:    stringLongestpalindrome (strings) {intn =s.length (); if(n = =0)return ""; BOOLf[ +][ +]; intStart =0, Max_len =0;  for(intj =0; J < N; J + +)             for(inti =0; I <= J; i++){                if(i = = J | | j-i >1&& f[i+1][j-1] && s[i] = = S[j] | | i +1= = J && s[i] = =S[j]) {F[i][j]=true; if(J-i +1>Max_len) {Max_len= J-i +1; Start=i; }                }ElseF[I][J] =false; }                returns.substr (Start, Max_len); }};

Leetcode:longest palindromic Substring

Related Article

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.