Problem: 5. 最长回文子串
题目描述
思路
1.状态定义:dp[i][j]表示s[i…j]是回文字符串(定义为bool类型若为true则表示是回文串);
2.状态初始化:所有长度为0的均为回文串,即dp[i][i] == true;
3.状态转移:若s[i] != s[j],则dp[i][j] == false,若s[i] = s[j],则dp[i][j] = dp[i + 1][j - 1]
复杂度
时间复杂度:
O ( N 2 ) O(N^2) O(N2);其中 N N N为字符串的长度
空间复杂度:
O ( N 2 ) O(N^2) O(N2)
Code
class Solution {
/**
* Longest Palindromic Substring
*
* @param s Given string
* @return String
*/
public String longestPalindrome(String s) {
int len = s.length();
if (len < 2) {
return s;
}
int maxLen = 1;
int begin = 0;
// dp[i][j] Indicates whether s[i..j] is a palindrome string
boolean[][] dp = new boolean[len][len];
// dp[i][j] Indicates whether s[i..j] is a palindrome string
for (int i = 0; i < len; ++i) {
dp[i][i] = true;
}
for (int L = 2; L <= len; ++L) {
for (int l = 0; l < len; ++l) {
// L and l can determine the right boundary, that is, r - l + 1 = L
int r = L + l - 1;
// If the right boundary is out of bounds, you can exit the current loop
if (r >= len) {
break;
}
if (s.charAt(l) != s.charAt(r)) {
dp[l][r] = false;
} else {
if (r - l < 3) {
dp[l][r] = true;
} else {
dp[l][r] = dp[l + 1][r - 1];
}
}
// As long as dp[i][L] == true is true, it means that
// the substring s[i..L] is a palindrome,
// in which case the palindrome length and starting position are recorded
if (dp[l][r] && r - l + 1 >= maxLen) {
maxLen = r - l + 1;
begin = l;
}
}
}
return s.substring(begin, begin + maxLen);
}
}