力扣算法 Java 刷题笔记【动态规划篇 DP 子序列类型问题】hot100(一) 最长回文子串 & 最长回文子序列 2
1. 最长回文子串(中等)
地址: https://leetcode-cn.com/problems/longest-palindromic-substring/
2021/12/26
做题反思:“” 和 null 的区别
Java空字符串(即““)和null的区别 “”是一个长度为 0 且占内存的空字符串,在内存中分配一个空间,可以使用 Object 对象中的方法。 例如: “”.toString () 等。 null 是空引用,表示一个对象的值,没有分配内存,调用 null 的字符串的方法会抛出空指针异常。
class Solution {
public String longestPalindrome(String s) {
String res = "";
for (int i = 0; i < s.length(); i++) {
String string1 = palindrome(s, i, i);
String string2 = palindrome(s, i, i + 1);
res = string1.length() > res.length() ? string1 : res;
res = string2.length() > res.length() ? string2 : res;
}
return res;
}
String palindrome(String s, int l, int r) {
while(l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
l--;
r++;
}
return s.substring(l + 1, r);
}
}

2. 最长回文子序列(中等)
地址: https://leetcode-cn.com/problems/longest-palindromic-subsequence/
2021/12/26
做题反思:明确dp数组的定义
class Solution {
public int longestPalindromeSubseq(String s) {
int m = s.length();
int[][] dp = new int[m][m];
for (int i = 0; i < m; i++) {
dp[i][i] = 1;
}
for (int i = m - 2; i >= 0; i--) {
for (int j = i + 1; j < m; j++) {
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1] + 2;
}else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][m - 1];
}
}


浙公网安备 33010602011771号