【每日一题】【奇偶分别中心扩展/动态规划】2022年2月5日-NC最长回文子串的长度
2024-10-21 16:02:52
描述
对于长度为n的一个字符串A(仅包含数字,大小写英文字母),请设计一个高效算法,计算其中最长回文子串的长度。
方法1:奇数偶数分别从中心扩展
import java.util.*; public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A string字符串
* @return int整型
*/
public int getLongestPalindrome (String A) {
int n = A.length();
int maxLen = Integer.MIN_VALUE;
for(int i = 0; i < n; i++) {
maxLen = Math.max(maxLen, getLen(i, i + 1, A));
maxLen = Math.max(maxLen, getLen(i - 1, i + 1, A));
}
return maxLen;
} public static int getLen(int l, int r, String A) {
while(l >= 0 && r <= A.length() - 1 && A.charAt(l) == A.charAt(r)) {
l--;
r++;
}
return r - l - 1;
}
}
方法2:动态规划【未做出来】
public class Solution {
public int getLongestPalindrome(String A) {
if (A.length()<=1) return A.length();
int n = A.length();
int[][] dp = new int[n][n];
int res = 1;
int len = A.length();
// 长度为 1 的串,肯定是回文的
for (int i = 0; i < n; i++) {
dp[i][i]=1;
}
// 将长度为 2-str.length 的所有串遍历一遍
for (int step = 2; step <= A.length(); step++) {
for (int l = 0; l < A.length(); l++) {
int r=l+step-1;
if (r>=len) break;
if (A.charAt(l)==A.charAt(r)) {
if (r-l==1) dp[l][r]=2;
else dp[l][r]=dp[l+1][r-1]==0?0:dp[l+1][r-1]+2;
}
res=Math.max(res,dp[l][r]);
}
}
return res;
}
}
最新文章
- 网站logo正确写法,个人拙见,不喜勿喷
- Python Day18
- poj3629
- OAF_开发系列29_实现OAF中批次处理迭代器RowSet/RowSetIterator(案例)
- 【Python】-【类解析】--【脚本实例】
- CardboardCamera Prefab 中文笔记
- 【UVa】11270 Tiling Dominoes
- 剑指offer系列24---数组中重复的数字
- ebay如何确定同一电脑登陆了多个账号,以及同一账号登陆过多台电脑
- input有许多,点击按钮使用form传递文本框的值
- <;!DOCTYPE>; 声明 引发的错误
- C3垂直居中均分
- console输出彩色字体
- 完整的Django入门指南学习笔记6
- kolla-ansible源码分析
- Linux查看当前使用的网卡 以及 查看某进程使用的网络带宽情况 以及 端口占用的情况
- 每月IT摘录201901
- win32 音视频相关 api
- pywin32记录备忘
- codeforces 444 C. DZY Loves Colors(线段树)