5. Longest Palindromic Substring
Copy Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
Copy class Solution {
public String longestPalindrome ( String s) {
if (s == null || s . isEmpty ()) return "" ;
int sLen = s . length ();
int longest = 0 , left = 0 ;
for ( int i = 0 ; i < sLen; i ++ ) {
for ( int j = i; j < sLen; j ++ ) {
if ( isPalindrome(s , i , j) && j - i + 1 > longest) {
longest = j - i + 1 ;
left = i;
}
}
}
return s . substring (left , left + longest);
}
private boolean isPalindrome ( String s , int left , int right) {
for ( int i = left , j = right; i <= j; i ++ , j -- ) {
if ( s . charAt (i) != s . charAt (j)) return false ;
}
return true ;
}
}
Copy class Solution {
public String longestPalindrome ( String s) {
if (s == null || s . isEmpty ()) return "" ;
int sLen = s . length ();
int longest = 0 , left = 0 ;
for ( int i = 0 ; i < sLen; i ++ ) {
// odd
int leftIndex = leftPalindromeIndex(s , i , i) ;
int palindromeLen = 2 * (i - leftIndex) + 1 ;
if (palindromeLen > longest) {
left = leftIndex;
longest = palindromeLen;
}
// even
leftIndex = leftPalindromeIndex(s , i , i + 1 ) ;
palindromeLen = 2 * (i - leftIndex + 1 );
if (palindromeLen > longest) {
left = leftIndex;
longest = palindromeLen;
}
}
return s . substring (left , left + longest);
}
private int leftPalindromeIndex ( String s , int left , int right) {
for (; left >= 0 && right < s . length (); left -- , right ++ ) {
if ( s . charAt (left) != s . charAt (right)) break ;
}
return left + 1 ;
}
}