Leetcode 5. Longest Palindromic Substring
2016-03-24 08:56
295 查看
Question
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.code
常规方式
/* 常规方法 */ public String longestPalindromeC(String s) { if (s == null || s.length() <= 1 || new StringBuilder(s).reverse().toString().equals(s)) { return s; } String result = ""; for (int i = 1; i < s.length(); i++) { int j = 1; //奇数对称情况 比如aba for (j = 1; i + j < s.length() && i - j >= 0 && s.charAt(i + j) == s.charAt(i - j); j++) ; String temp1 = s.substring(i - j + 1, i + j); if (temp1.length() > result.length()) { result = temp1; } //偶数情况 aa类型 if (s.charAt(i) == s.charAt(i - 1)) { for (j = 1; i + j < s.length() && i - j - 1 >= 0 && s.charAt(i + j) == s.charAt(i - j - 1); j++) ; String temp2 = s.substring(i - j, i + j); if (temp2.length() > result.length()) { result = temp2; } } } return result; }
DP方式
/* 标记数组加DP方法 */ public String longestPalindromeDP(String s) { if (s == null || s.length() == 0) { return s; } boolean[][] flag = new boolean[s.length()][s.length()]; int start = 0; int end = 0; for (int i = 0; i < s.length(); i++) { for (int j = 0; j <= i; j++) { flag[j][i] = s.charAt(j) == s.charAt(i) && (i - j <= 2 || flag[j + 1][i - 1]); if (flag[j][i]) { if (end - start < i - j) { start = j; end = i; } } } } return s.substring(start, end + 1); }
优化DP
/* DP方法 */ public String longestPalindromeDPB(String s) { int[] p = new int[2048]; StringBuilder t = new StringBuilder("$"); for (int i = 0; i < s.length(); ++i) { t.append('#'); t.append(s.charAt(i)); } t.append("#_"); // mx为已判断回文串最右边位置,id为中间位置,mmax记录p数组中最大值 int mx = 0, id = 0, mmax = 0; int right = 0; for (int i = 1; i < t.length() - 1; i++) { p[i] = mx > i ? Math.min(p[2 * id - i], mx - i) : 1; while (t.charAt(i + p[i]) == t.charAt(i - p[i])) p[i]++; if (i + p[i] > mx) { mx = i + p[i]; id = i; } if (mmax < p[i]) { mmax = p[i]; right = i; } } // 最长为mmax - 1 return s.substring(right / 2 - mmax / 2, right / 2 - mmax / 2 + mmax - 1); }
马拉车算法
马拉车算法
相关文章推荐
- BZOJ-2118 墨墨的等式(好题) 最短路+乱搞
- Java中字符编码格式详解
- Python logical XOR
- 第四周【递归求出两个数的最大公约数】
- linux的scp命令可以在linux服务器之间复制文件和目录
- CentOS6.7安装Python3.4
- yum命令使用方法
- RippleView(仿照5.0点击有波浪效果)
- <a href="#"><a herf="javascript:void(0)">...几种方法的使用与总结
- opencv学习笔记:一些函数、类的使用方法
- Binary bitwise operations
- Mac OSX 证书都显示为失效的解决办法
- 广度优先懵逼VS深度优先懵逼
- HR最喜欢这样的简历
- 动态更改js引入脚本
- 第3周项目9-Fibnacci序列
- c++第二次试验
- C++实验2-两点距离
- 1001. A+B Format (20)
- 排序算法系列:插入排序算法