Longest palindromic Substring

Source: Internet
Author: User

https://oj.leetcode.com/problems/longest-palindromic-substring/

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.

A relatively simple solution, traversing the array from left to right, with the current number as the axis, or two of the same number as the axis, (two cases), spread to both sides. The terminating condition is that it spreads to the beginning or end of the array, or the two segments of the element are inconsistent. Records the length of each case, and finally returns the longest start and end coordinates. The solution is mainly to pay attention to two kinds of situations. The time complexity is O (n^2).

 Public classSolution { Publicstring Longestpalindrome (string s) {intStart = 0; intEnd = 0; intMaxstart = 0; intMaxend = 0; intMaxLength = 0; //with a number as the axis of symmetry         for(inti = 0; I < s.length (); i++) {Start=i; End=i;  while(Start >= 0 && End < S.length () && s.charat (start) = =S.charat (end)) {Start--; End++; } Start++; End--; intLength = End-start + 1; if(Length >maxLength) {MaxLength=length; Maxstart=start; Maxend=end; }        }        //with some two symmetrical        if(S.length () > 1){             for(inti = 1; I < s.length (); i++){                if(S.charat (i) = = S.charat (i-1) ) {Start= I-1; End=i;  while(Start >= 0 && End < S.length () && s.charat (start) = =S.charat (end)) {Start--; End++; }} Start++; End--; intLength = End-start + 1; if(Length >maxLength) {MaxLength=length; Maxstart=start; Maxend=end; }            }        }        returnS.substring (Maxstart, Maxend + 1); }}

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.