[Leetcode] [Java] Longest palindromic Substring

Source: Internet
Author: User

Topic:

Given A stringS, find the longest palindromic substring inS. Assume that maximum length ofSis, and there exists one unique longest palindromic substring.

Test instructions

Given the string s, locate the longest palindrome substring in the string. Assume that the maximum length of this substring is 1000, and that the longest palindrome string is present and unique.

Algorithm Analysis:

The palindrome string is symmetrical in the center axis, so if we start with subscript I, we use 2 pointers to expand the two sides of I to determine whether it is equal
Note that the string of characters has odd-even symmetry

The code is as follows:

    Public String Longestpalindrome (string s)     {if (s==null| | S.length () <=1) return s; String maxres= ""; String res= "";    for (int i=0;i<s.length (); i++) {res=getnum (s,i,i);//palindrome string with I as Center if (maxres.length () <res.length ()) maxres=res;res= Getnum (s,i,i+1);//palindrome string with i,i+1 as the center if (maxres.length () <res.length ()) Maxres=res;} return maxres;    } private static string Getnum (string s, int begin,int end) {while (Begin>=0&&end<=s.length ()-1) {if ( S.charat (BEGIN) ==s.charat (end) {begin--;end++;} else break;} Return s.substring (begin+1,end);}


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

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