当前位置:网站首页>【LeetCode】最长回文子序列(动态规划)
【LeetCode】最长回文子序列(动态规划)
2022-08-03 23:00:00 【小七mod】
一、题目
给你一个字符串 s ,找出其中最长的回文子序列,并返回该序列的长度。
子序列定义为:不改变剩余字符顺序的情况下,删除某些字符或者不删除任何字符形成的一个序列。
示例 1:
输入:s = "bbbab" 输出:4 解释:一个可能的最长回文子序列为 "bbbb" 。
示例 2:
输入:s = "cbbd" 输出:2 解释:一个可能的最长回文子序列为 "bb" 。
提示:
1 <= s.length <= 1000
s
仅由小写英文字母组成
二、代码
class Solution {
public int longestPalindromeSubseq(String s) {
// 判空
if (s == null || s.length() == 0) {
return 0;
}
// 将字符串转换为字符数组
char[] str = s.toCharArray();
// 创建dp数组
int n = str.length;
int[][] dp = new int [n][n];
// 赋初值,对两个对角线赋初值
dp[n - 1][n - 1] = 1;
for (int i = 0; i < n - 1; i++) {
dp[i][i] = 1;
dp[i][i + 1] = str[i] == str[i + 1] ? 2 : 1;
}
// 按照动态转移方程对dp数组进行复制,沿对角线方向进行复制
for (int i = 2; i < n; i++) {
// 之所以这里用j表示列,是因为列的范围更好控制,因为所有的对角线最后一个节点一定都是最后一列,是固定不变的
for (int j = i; j < n; j++) {
int r = j;
int l = r - i;
// 动态转移方程
dp[l][r] = Math.max(dp[l + 1][r], dp[l][r - 1]);
if (str[l] == str[r]) {
dp[l][r] = Math.max(dp[l][r], dp[l + 1][r - 1] + 2);
}
}
}
// 返回结果
return dp[0][n - 1];
}
}
三、解题思路
利用动态规划的思路进行解题。利用已经得出的初值来逐渐退出全部可能的结果。
边栏推荐
- RPA助力商超订单自动化!
- The principle and use of AOSP CameraLatencyHistogram
- CAS: 178744-28-0, mPEG-DSPE, DSPE-mPEG, methoxy-polyethylene glycol-phosphatidylethanolamine supply
- 软测人每个阶段的薪资待遇,快来康康你能拿多少?
- Software testing is seriously involution, how to improve your competitiveness?
- complete binary tree problem
- 软件测试内卷严重,如何提升自己的竞争力呢?
- Take an example of a web worker
- 走迷宫 BFS
- Interpretation of ML: A case of global interpretation/local interpretation of EBC model interpretability based on titanic titanic rescued binary prediction data set using interpret
猜你喜欢
FinClip,助长智能电视更多想象空间
软件测试内卷严重,如何提升自己的竞争力呢?
[N1CTF 2018] eating_cms
逆波兰表达式求值
OPC UA 与IEC61499 深度融合(1)
"Digital Economy Panorama White Paper" Financial Digital User Chapter released!
Lift, Splat, Shoot: Encoding Images from Arbitrary Camera Rigs by Implicitly Unprojecting to 3D 论文笔记
Republish the lab report
Pytest学习-setup/teardown
藏宝计划TreasureProject(TPC)系统模式开发技术原理
随机推荐
BMN: Boundary-Matching Network for Temporal Action Proposal Generation Reading Notes
牛客2022 暑期多校3 H Hacker(SAM + 线段树查询区间内部最大子段和)
End-to-End Lane Marker Detection via Row-wise Classification
代码随想录笔记_动态规划_416分割等和子集
pikachu Over permission
用两个栈模拟队列
CAS:178744-28-0,mPEG-DSPE,DSPE-mPEG,甲氧基-聚乙二醇-磷脂酰乙醇胺供应
Another MySQL masterpiece published by Glacier (send the book at the end of the article)!!
utils 定时器
云平台建设解决方案
override learning (parent and child)
Golang Chapter 2: Program Structure
Storage engine written by golang, based on b+ tree, mmap
Nine ways to teach you to read the file path in the resources directory
Kotlin - 扩展函数和运算符重载
RPA助力商超订单自动化!
IELTS essay writing template
How many way of calling a function?
Embedded Systems: Clocks
生成器版和查看器版有什么区别?