O(n)时间复杂度求最长回文串
来源:互联网 发布:淘宝2016版本下载6.7.2 编辑:程序博客网 时间:2024/06/07 20:48
该算法思想转载自:http://zhuhongcheng.wordpress.com/2009/08/02/a-simple-linear-time-algorithm-for-finding-longest-palindrome-sub-string/
1、问题描述
对于给定的一的个字符串,求出它的最长回文串长度。(回文串的定义在这里就不缀述了)
2、解决思路
先将特殊字符'#'插入字符串中,例如原字符串str="abaaca",得插入'#'后的字符串为:newStr="#a#b#a#a#c#a#",这种方式方法的好处将奇数长度回文串与偶数长度回文串统一起来考虑了,然后用一个辅助数组P记录以每个字符为中心的最长回文串的信息。P[id]记录的是以字符newStr[id]为中心的最长回文串,当以str[id]为第一个字符,这个最长回文串向右延伸了P[id]个字符,P[id]-1就是该回文子串在原串中的长度。
3、与算法相关的图片(好好理解理解)
4、JAVA代码
public class LongestPalindromeString {private String str=""; //保存带'#'字符串public LongestPalindromeString(String str) {super();this.str = splitStr(str);}private String splitStr(String str){ //将原串转换成带'#'的字符串 StringBuffer buffer=new StringBuffer(); buffer.append("$"); //将str[0]设为'$',使字符串从索引1开始 for(int i=0;i<str.length();i++){ buffer.append("#"); buffer.append(str.charAt(i)); } buffer.append("#"); return buffer.toString();}public int[] getPalindrome(){int max=0,id=1;int[] p=new int[str.length()]; //p[id]用于保存每个str[id]为中心的最长回文串for(int i=1;i<str.length();i++){if(max>i){p[i]=min(p[2*id-i],max-i); //P[2*id-i]代表上述图片中出现的第一种情况,即上半个图的情况}else{ //max-i表示上述图片中出现的第二种情况,即下半个图的情况p[i]=1;}while(i+p[i]<str.length()&&str.charAt(i-p[i])==str.charAt(i+p[i])){p[i]++;}if(i+p[i]>max){max=i+p[i];id=i;}}return p;}private int min(int i, int j) {// TODO Auto-generated method stubreturn i<j?i:j;}public static void main(String[] args) {LongestPalindromeString lonPa=new LongestPalindromeString("adfffd");int[] result=lonPa.getPalindrome();for(int i=0;i<result.length;i++)System.out.print(result[i]);}}
每天学习一点点
0 0
- O(n)时间复杂度求最长回文串
- 求最长回文子串,O(n)复杂度
- 最长回文子串 Manacher算法 时间复杂度O(N)
- 【最长回文子串】Manache算法,O(N)时间复杂度
- Manacher算法,最长回文串,时间复杂度O(n)
- O(n)时间求字符串的最长回文子串
- O(n)时间求字符串的最长回文子串
- Manacher算法O(n) 时间复杂度求最长回文字串及其长度
- 最长回文(Manacher算法 时间复杂度O(n))
- 最长回文字串 Manacher算法 时间复杂度O(N)
- HDU3068-最长回文---O(n)时间求最长回文子串
- O(n) 求 最长回文子串
- O(n) 求 最长回文子串
- O(n)求最长回文子串
- O(n)求最长回文子串
- O(n) 求 最长回文子串
- O(n) 求 最长回文子串
- O(n) 求 最长回文子串
- java对象的强引用,软引用,弱引用和虚引用
- iaas paas saas (2)
- 微软Surface Pro 3取代笔记本只差这一步
- 股票买卖之多次交易最大利润
- 如何在Sublime text中运行PHP文件
- O(n)时间复杂度求最长回文串
- 哪些编程语言、框架/平台最受企业青睐?
- 强烈推荐shop++3.0源代码
- VMware虚拟机瘦身技巧
- 查找练习 hash——出现过的数字(哈希查找)
- C3P0连接池配置解决MySQL连接的空闲时间超过8小时后自动断开连接的问题
- .NET MVC上传一个文件,用NPOI解析后在界面上显示
- 侍从骑士考核
- jdk的环境变量配置