- 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 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
思路
利用动态规划:
dp[i][i+k]=1表示str下标为i到i+k组成的子串为回文串。
因此,状态转移方程如下:
dp[i][i+k] = dp[i+1][i+k-1],str.charAt(i) == str.char[i+k]
dp[i][i+k] = 0,str.charAt(i) != str.char[i+k]
即,如果某个字符串的左右两端的字符相同,则当除去两端的字符的子串为回文串时该字符串为回文子串。
代码
class Solution {
public String longestPalindrome(String str) {
if(str == null || str.length() == 0){
return "";
}
int n = str.length();
int[][] dp = new int[n][n];
int start = 0,end = 0;
int i=0,k=0;
for(i = 0;i < n - 1;i++){
//初始化间距为0的情况(即单个字符也视为回文子串))
dp[i][i] = 1;
//间距为1的情况
if(str.charAt(i) == str.charAt(i+1)){
dp[i][i+1] = 1;
start = i;
end = i + 1;
}
}
//间距为2到n-1的情况
for (k = 2; k < n; k++) {
for (i = 0; i + k < n; i++) {
if (str.charAt(i) == str.charAt(i + k) && dp[i+1][i + k - 1] == 1) {
dp[i][i + k] = 1;
start = i;
end = i + k;
// System.out.println("("+start+","+end+")");
}
}
}
return str.substring(start,end+1);
}
}