Leetcode 005 Longest palindromic Substring-java

Source: Internet
Author: User

Given A string s, find the longest palindromic substring in S. Assume that the maximum length of S is 1000.

Example:

Input: "Babad" Output: "Bab" note: "ABA" is also a valid answer.

Example:

Input: "CBBD" Output: "BB"

Positioning: Medium problem

Finding the longest palindrome substring in a given string, you can take a traversal of each character to determine if it is possible to generate a text string in its center, once it is possible to extend to both ends. There are two situations, one is centered on one letter, the other is centered on two identical letters, and is recorded and judged to be the longest when extended to the limit.

The Java implementation is as follows:

1  Public classSolution {2      Publicstring Longestpalindrome (string s) {3         intlen=s.length ();4         if(len<=1){5             returns;6         }7         intLen=1,maxlen=1;8         inti,j;9String str=string.valueof (S.charat (0));Ten         if(S.charat (0) ==s.charat (1)){ OneStr=s.substring (0,2); Amaxlen=2; -         } -          for(i=1;i<len-1;i++){ the             if(S.charat (i-1) ==s.charat (i+1)){ -J=1; -                  while(I-j>=0&&i+j<len&&s.charat (I-J) ==s.charat (i+j)) { -J + +; +                 } -j--; +Len=2*j+1; A                 if(len>maxlen) { atmaxlen=Len; -Str=s.substring (i-j,i+j+1); -                 } -             } -             if(S.charat (i) ==s.charat (i+1)){ -J=1; in                  while(I-j+1>=0&&i+j<len&&s.charat (i-j+1) ==s.charat (i+j)) { -J + +; to                 } +j--; -len=2*J; the                 if(len>maxlen) { *maxlen=Len; $Str=s.substring (i-j+1,i+j+1);Panax Notoginseng                 } -             } the         } +         returnstr; A     } the}

Leetcode 005 Longest palindromic Substring-java

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.