首页 > 代码库 > LeetCode Longest Palindromic Substring 最长回文子串

LeetCode Longest Palindromic Substring 最长回文子串

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length ofS is 1000, and there exists one unique longest palindromic substring.(最长回文子串)

中心扩展法:

public class Solution {
    public String longestPalindrome(String s) {
           int length = s.length();
           int maxlength = 0;
           int start=0;
           
               for(int i=0;i<length;i++)//子串长度是奇数
               {
                   int j=i-1,k=i+1;
                   while(j>=0&&k<length&&(s.charAt(j)==s.charAt(k)))
                   {
                         if(k-j+1>maxlength)
                         {
                           maxlength = k-j+1;
                           start = j;
                         }
                         j--;
                         k++;
                   }
                   
                
               }
           
               for(int i=0;i<length;i++)  //子串长度是偶数
               {
                   int j=i,k=i+1;
                   while(j>=0&&k<length&&s.charAt(j)==s.charAt(k))
                   {
                       if(k-j+1>maxlength)
                       {
                       maxlength = k-j+1;
                       start = j;
                       }
                       j--;
                       k++;
                   }
                   
               }
               if(maxlength>0)
               {
               return s.substring(start,start+maxlength);
               }
               return s;
           }
            
        }


LeetCode Longest Palindromic Substring 最长回文子串