当前位置:网站首页>【LeetCode】最长回文子序列(动态规划)
【LeetCode】最长回文子序列(动态规划)
2022-08-03 23:00:00 【小七mod】
一、题目
给你一个字符串 s ,找出其中最长的回文子序列,并返回该序列的长度。
子序列定义为:不改变剩余字符顺序的情况下,删除某些字符或者不删除任何字符形成的一个序列。
示例 1:
输入:s = "bbbab" 输出:4 解释:一个可能的最长回文子序列为 "bbbb" 。
示例 2:
输入:s = "cbbd" 输出:2 解释:一个可能的最长回文子序列为 "bb" 。
提示:
1 <= s.length <= 1000s仅由小写英文字母组成
二、代码
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];
}
}三、解题思路
利用动态规划的思路进行解题。利用已经得出的初值来逐渐退出全部可能的结果。
边栏推荐
- 3D 语义分割——2DPASS
- 举一个 web worker 的例子
- 生成器版和查看器版有什么区别?
- golang写的存储引擎,基于b+树,mmap
- 使用tf.image.resize() 和tf.image.resize_with_pad()调整图像大小
- Kotlin - 扩展函数和运算符重载
- Nine ways to teach you to read the file path in the resources directory
- websocket多线程发送消息报错TEXT_PARTIAL_WRITING--自旋锁替换synchronized独占锁的使用案例
- log4j-slf4j-impl cannot be present with log4j-to-slf4j
- 直播预告 | 构建业务智联,快速拥抱财务数字化转型
猜你喜欢

最小化安装debian11

云平台建设解决方案

Embedded Systems: GPIO

完全二叉树问题

FinClip最易用的智能电视小程序

Canvas App中点击图标生成PDF并保存到Dataverse中

encapsulation, package, access modifier, static variable

Another MySQL masterpiece published by Glacier (send the book at the end of the article)!!

Recognized by International Authorities | Yunzhuang Technology was selected in "RPA Global Market Pattern Report, Q3 2022"

OPC UA 与IEC61499 深度融合(1)
随机推荐
2022-08-03 Oracle executes slow SQL-Q17 comparison
On the Qixi Festival of 2022, I will offer 7 exquisite confession codes, and at the same time teach you to quickly change the source code for your own use
P1996 约瑟夫问题
Testng listener
易观分析:2022年Q2中国网络零售B2C市场交易规模达23444.7亿元
Take an example of a web worker
Analysys Analysis: The transaction scale of China's online retail B2C market in Q2 2022 will reach 2,344.47 billion yuan
for loop exercises
complete binary tree problem
What is memoization and what is it good for?
Republish the lab report
Zilliz 2023 秋季校园招聘正式启动!
utlis 线程池
Network basic learning series four (network layer, data link layer and some other important protocols or technologies)
Creo 9.0二维草图的诊断:加亮开放端点
【RYU】rest_router.py源码解析
Click the icon in Canvas App to generate PDF and save it to Dataverse
The principle and use of AOSP CameraLatencyHistogram
Lift, Splat, Shoot: Encoding Images from Arbitrary Camera Rigs by Implicitly Unprojecting to 3D 论文笔记
一个函数有多少种调用方式?