Java [Leetcode 5] Longest palindromic Substring

Source: Internet
Author: User

Problem Description:

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.

Problem Solving Ideas:

Traversal method with a time complexity of O (n). It starts from the beginning of the string, and then spreads from the position to the sides in each traversal until the longest sub-palindrome is found. You also need to consider the case of odd and even strings.

The code is as follows:

1  Public classSolution {2     Publicstring Longestpalindrome (string s) {3         intn =s.length ();4String longest = s.substring (0, 1);5 6         if(s = =NULL|| S.length () = = 0)7             return NULL;8          for(inti = 0; I < n; i++) {9String P1 =Expandfromcenter (S, I, I);Ten             if(P1.length () >longest.length ()) OneLongest =P1; AString P2 = expandfromcenter (s, I, i + 1); -             if(P2.length () >longest.length ()) -Longest =P2; the         } -         returnlongest; -     } -  +      PublicString Expandfromcenter (String s,intC1,intC2) { -         intHead =C1; +         intTail =C2; A         intm =s.length (); at  -          while(Head >= 0 && tail < m && S.charat (head) = =S.charat (tail)) { -head--; -tail++; -         } -         returnS.substring (head + 1), tail); in     } -}

Java [Leetcode 5] 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.