提取最长回文子串

来源:互联网 发布:程序员逛的网站 编辑:程序博客网 时间:2024/06/08 04:23

题目描述

给定一个字符串,找出该字符串的最长回文子串。回文字符串指的就是从左右两边看都一样的字符串,如aba,cddc都是回文字符串。字符串abbacdc存在的回文子串有abba和cdc,因此它的最长回文子串为abba。

中心法求最长回文子串

还有一个更简单的方法可以使用O(N^2)时间、不需要额外的空间求最长回文子串。我们知道回文字符串是以字符串中心对称的,如abba以及aba等。一个更好的办法是从中间开始判断,因为回文字符串以字符串中心对称。一个长度为N的字符串可能的对称中心有2N-1个,至于这里为什么是2N-1而不是N个,是因为可能对称的点可能是两个字符之间,比如abba的对称点就是第一个字母b和第二个字母b的中间。因此可以依次对2N-1个中心点进行判断,求出最长的回文字符串即可。根据该思路可以写出下面的代码。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package edu.pku.ss.hlj;  
  2.   
  3. public class LongestPalindrome {  
  4.     public static void main(String[] args) {  
  5.         String str = "abcddcc";  
  6.   
  7.         String result = getPalindrome(str);  
  8.         System.out.println(result);  
  9.   
  10.     }  
  11.   
  12.     /** 
  13.      * 判断一个字符数组从某一个或两个点开始向两端拓展,是否是回文串,是则返回该子串 
  14.      *  
  15.      * @param ch 
  16.      * @param i 
  17.      * @param j 
  18.      * @return 
  19.      */  
  20.     public static String getEvery(char[] ch, int i, int j) {  
  21.         int length = ch.length;  
  22.         while (i >= 0 && j <= length - 1 && ch[i] == ch[j]) {  
  23.             i--;  
  24.             j++;  
  25.         }  
  26.         return String.valueOf(ch).substring(i + 1, j);// 不可以用ch.toString(),这个方法返回的不是字符数组对应的字符串,而是一个内存地址,  
  27.         // 且此处无论是前面边界退出还是两端值不等退出都应该将ij的值回退,所以sub这两端。  
  28.     }  
  29.   
  30.     /** 
  31.      * 遍历原数组,提取出最长的回文子串 
  32.      *  
  33.      * @param s 
  34.      * @return 
  35.      */  
  36.     public static String getPalindrome(String s) {  
  37.         char[] ch = s.toCharArray();  
  38.         String str = " ";  
  39.         String re = "";  
  40.         for (int i = 0; i < ch.length; i++) {  
  41.             re = getEvery(ch, i, i); // 当以一个字符为中轴也就是回文串为奇数时  
  42.             if (re.length() > str.length()) {  
  43.                 str = re;  
  44.             }  
  45.             re = getEvery(ch, i, i + 1); // 当以当前和他后一个字符为轴心,也就是回文串为偶数时  
  46.             if (re.length() > str.length()) {  
  47.                 str = re;  
  48.             }  
  49.         }  
  50.         return str;  
  51.     }  
  52. }  
0 0
原创粉丝点击