5 Longest Palindromic Substring
1. Question
Given a strings, find the longest palindromic substring ins. You may assume that the maximum length ofsis 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
2. Implementation
(1) DP
思路: 我们用一个2维 boolean数组dp[i][j]判断substring s[i...j]是否为Palindrome, 如果dp[i][j]是true的话,比较当前得到的是palindrome的substring和res的长度大小,比res长度大的话则更新res
class Solution {
public String longestPalindrome(String s) {
int n = s.length();
String res = null;
boolean[][] dp = new boolean[n][n];
for (int j = 0; j < n; j++) {
for (int i = j; i >= 0; i--) {
if (s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1])) {
dp[i][j] = true;
}
if (dp[i][j] && (res == null || j - i + 1 > res.length())) {
res = s.substring(i, j + 1);
}
}
}
return res;
}
}
3. Time & Space Complexity
DP: 时间复杂度O(n^2), 空间复杂度O(n^2)
Last updated
Was this helpful?