LeetCode 005 Longest Palindromic Substring - Java

來源:互聯網
上載者:User

標籤:max   note   content   --   i++   log   string   entry   pre   

Given a string s, find the longest palindromic substring in s. You may 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"

 

定位:中等題

找到給定的字串中的最長的迴文子串,可以採取遍曆每一個字元,判斷有沒有可能以其為中心產生迴文字串,一旦可能就向兩端擴充。有兩種情況,一種是以一個字母為中心,另一種為以兩個相同字母為中心,當擴充到極限後記錄並判斷是不是最長的。

 

Java實現如下:

 1 public class Solution { 2     public String longestPalindrome(String s) { 3         int len=s.length(); 4         if(len<=1){ 5             return s; 6         } 7         int Len=1,maxLen=1; 8         int i,j; 9         String str=String.valueOf(s.charAt(0));10         if(s.charAt(0)==s.charAt(1)){11             str=s.substring(0,2);12             maxLen=2;13         }14         for(i=1;i<len-1;i++){15             if(s.charAt(i-1)==s.charAt(i+1)){16                 j=1;17                 while(i-j>=0&&i+j<len&&s.charAt(i-j)==s.charAt(i+j)){18                     j++;19                 }20                 j--;21                 Len=2*j+1;22                 if(Len>maxLen){23                     maxLen=Len;24                     str=s.substring(i-j,i+j+1);25                 }26             }27             if(s.charAt(i)==s.charAt(i+1)){28                 j=1;29                 while(i-j+1>=0&&i+j<len&&s.charAt(i-j+1)==s.charAt(i+j)){30                     j++;31                 }32                 j--;33                 Len=2*j;34                 if(Len>maxLen){35                     maxLen=Len;36                     str=s.substring(i-j+1,i+j+1);37                 }38             }39         }40         return str;41     }42 }

LeetCode 005 Longest Palindromic Substring - Java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.