子串提取

来源:互联网 发布:郑州淘宝店铺装修设计 编辑:程序博客网 时间:2024/06/06 00:43
/*串“abcba”以字母“c”为中心左右对称;串“abba”是另一种模式的左右对称。
这两种情况我们都称这个串是镜像串。特别地,只含有1个字母的串,可以看成是第一种模式的镜像串。
一个串可以含有许多镜像子串。我们的目标是求一个串的最大镜像子串(最长的镜像子串),
如果有多个最大镜像子串,对称中心靠左的优先选中。

例如:“abcdeefghhgfeiieje444k444lmn”的最大镜像子串是:“efghhgfe”*/

--------------------------------------------------code-------------------------------------------------------------------------------------

public class AL15 {public static void main(String[] args) {String str="abcdeefghhgfeiieje444k444lmn";System.out.println(getMaxStr(str));}public static String getMaxStr(String s){String max="";char[] ch=s.toCharArray();int i=0;//while((i++)<ch.length)//exceptionfor(i=0;i<ch.length;i++){//abcba第1种对称模式int posi=1;try{for(;;){if(ch[i-posi]!=ch[i+posi])    break;posi++;}}catch(Exception e ){}String str1=s.substring(i-posi+1,i+posi);//abba第2种对称模式 posi=0; try{for(;;)//for(;;) = while(true) 这是一个无限循环,直到遇到指定条件(例如:break)跳出无限循环{if(ch[i-posi]!=ch[i+posi+1])break;posi++;} } catch(Exception e){}String str2=s.substring(i-posi+1,i+posi+1);if(str1.length()>max.length())max=str1;if(str2.length()>max.length())max=str2;}return max;}}