描述
对于长度为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;
}
}

最新文章

  1. 网站logo正确写法,个人拙见,不喜勿喷
  2. Python Day18
  3. poj3629
  4. OAF_开发系列29_实现OAF中批次处理迭代器RowSet/RowSetIterator(案例)
  5. 【Python】-【类解析】--【脚本实例】
  6. CardboardCamera Prefab 中文笔记
  7. 【UVa】11270 Tiling Dominoes
  8. 剑指offer系列24---数组中重复的数字
  9. ebay如何确定同一电脑登陆了多个账号,以及同一账号登陆过多台电脑
  10. input有许多,点击按钮使用form传递文本框的值
  11. &lt;!DOCTYPE&gt; 声明 引发的错误
  12. C3垂直居中均分
  13. console输出彩色字体
  14. 完整的Django入门指南学习笔记6
  15. kolla-ansible源码分析
  16. Linux查看当前使用的网卡 以及 查看某进程使用的网络带宽情况 以及 端口占用的情况
  17. 每月IT摘录201901
  18. win32 音视频相关 api
  19. pywin32记录备忘
  20. codeforces 444 C. DZY Loves Colors(线段树)

热门文章

  1. 8.maven上传jar包以及SNAPSHOT的一个坑
  2. C语言:类型存储
  3. NOIP2011 提高组 聪明的质监员(二分+前缀和)
  4. vue2使用组件进行父子互相传值的sync语法糖方法和原生方法
  5. Java学习之路:快捷键
  6. vue+element-ui后台管理系统模板
  7. python学习笔记---流程控制
  8. 一天五道Java面试题----第六天(1)
  9. python信息检索实验之向量空间模型与布尔检索
  10. golang中的锁竞争问题