標籤: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