- Longest Palindromic Substring
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”
class Solution {
public String longestPalindrome(String s) {
int maxLen = 0;
int index = 0;
int n = s.length();
boolean[][] dp = new boolean[n][n];
for(int len = 0; len < n; len++){
for(int i = 0; i < n-len; i++){
if(len == 0)
dp[i][i+len] = true;
else if(len == 1)
dp[i][i+len] = s.charAt(i) == s.charAt(i+len);
else
dp[i][i+len] = dp[i+1][i+len-1] && s.charAt(i) == s.charAt(i+len);
if(dp[i][i+len] == true){
maxLen = Math.max(maxLen, len);
index = i;
}
}
}
return s.substring(index, index+maxLen+1);
}
}